Home > OS >  Does move constructor only affect the memory space pointed to by the pointer member of the class?
Does move constructor only affect the memory space pointed to by the pointer member of the class?

Time:02-10

For example, this Code:

struct President  
{  
    std::string name;  
    std::string country;  
    int year;  

    President(std::string p_name, std::string p_country, int p_year)  
        : name(std::move(p_name)), country(std::move(p_country)), year(p_year)  
    {  
        std::cout << "--constructed\n";  
    }
    /*
    President(const President& other)
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
    */
    President(const President& other)
        : name(other.name), country(other.country), year(other.year)
    {
        std::cout << "--copy constructed\n";
    }
    President(President&& other)  
        : name(std::move(other.name)), country(std::move(other.country)), year(other.year)  
    {
        std::cout << "--moved\n";  
    }  
    ~President()
    {  
        cout << "\n"<< &name << " " << country << endl;
        std::cout << "--destruct\n";  
    }
    President& operator=(const President& other);  
};

Whether it is a move constructor or a copy constructor, they will cause the values of the three data members to be stored in the new memory, and the old memory will be released.

And my meaning is right?

CodePudding user response:

And my meaning is right?

Sorry, no. Your move constructor will work as you describe, in that it will 'steal' the contents of the name and country member variables from other, but the copy constructor will not. std::move does nothing with a const object and you should remove it from your copy constructor. After all, the operative word is copy, right?

It's worth noting that you don't need to write your own copy or move constructors at all here ('rule of zero'). The default constructors synthesized by the compiler will work just fine. Oh, and std::move on a primitive type such as an int also does nothing - the variable will just be copied whether you include it or not.

  • Related