0

I have two structures setup like so (simplified with std::string as their only data for example-sake - I know in this context a pointer to an std::string is pointless, excuse the pun):

Edit: To get to the jist of things, see the following function:

ItemData::void setSubItemData(SubItemData&& data, unsigned int n)
#include <string>
using std::string;

struct SubItemData
{
    // Default constructor
    SubItemData()
    {
        m_data = nullptr;
    }
    // Constructor for const char* ("Hello")
    SubItemData(const char* data)
    {
        m_data = new string(data);
    }
    // Copy assignment operator
    SubItemData& operator=(const SubItemData& other)
    {
        if (this == &other)
        {
            return *this;
        }
        delete m_data;
        m_data = new string(*other.m_data);
        return *this;
    }
    // Move assignment operator
    SubItemData& operator=(SubItemData&& other) noexcept
    {
        if (this == &other)
        {
            return *this;
        }
        m_data = other.m_data;
        other.m_data = nullptr;
        return *this;
    }

    // Member variable
    string* m_data;
};

struct ItemData
{
    void setSubItemData(const SubItemData& data, unsigned int n)
    {
        m_subItems[n] = data;
    }
    void setSubItemData(SubItemData&& data, unsigned int n)
    {
        m_subItems[n] = data;   // why does the copy asignment operator get called, when "data" is an r-value reference?
    }
    void makeAndMove(SubItemData data, unsigned int n)
    {
        setSubItemData(std::move(data), n);
    }
    SubItemData m_subItems[3];
};

However when I call makeAndMove (which calls the setSubItemData overload with an r-value reference) like so, my copy assignment operator gets called, and not my move assignment operator (determined using Visual Studio's breakpoints):

int main()
{
    ItemData* mainDataInstance = new ItemData();
    mainDataInstance->makeAndMove("Hello", 0);

    return 0;
}

Why is my move assignment operator not being called instead?

Gary Allen
  • 1,218
  • 1
  • 13
  • 28
  • You need `m_subItems[n] = std::move(data);` in `ItemData::setSubItemData(SubItemData&&, unsigned int)`. The linked duplicate explains why this is necessary. – cdhowie Jun 29 '20 at 14:30
  • @cdhowie Sorry for the duplicate... should've searched for longer! Thank you, this makes sense and answers my question. – Gary Allen Jun 29 '20 at 14:33
  • 1
    No problem! It's hard to know exactly what to search for when you don't know what the problem is. – cdhowie Jun 29 '20 at 14:33

0 Answers0