Is it necessary to define move constructors from different classes?

非 Y 不嫁゛ 提交于 2019-12-04 01:48:09

Yes, but no. Your code should just be this:

struct X
{
    Y y_;

    X(Y y) : // either copy, move, or elide a Y
    y_(std::move(y)) // and move it to the member
    {} 
};

If you ever say in design "I need my own copy of this data"*, then you should just take the argument by value and move it to where it needs to be. It isn't your job to decide how to construct that value, that's up to the available constructors for that value, so let it make that choice, whatever it is, and work with the end result.

*This applies to functions too, of course, for example:

void add_to_map(std::string x, int y) // either copy, move or elide a std::string
{
    // and move it to where it needs to be
    someMap.insert(std::make_pair(std::move(x), y));
}

Note that is applied in C++03 too, somewhat, if a type was default constructible and swappable (which is all moving does anyway):

// C++03
struct X
{
    std::string y_;

    X(std::string y) // either copy or elide a std::string
    {
        swap(y_, y); // and "move" it to the member
    } 
};

Though this didn't seem to be as widely done.

Yes, it is necessary. A const ref can only be a copy, not a move.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!