是否有必要从不同的类定义移动构造函数?

Ben*_*ley 11 c++ rvalue-reference move-semantics c++11

考虑以下:

struct X
{
    Y y_;

    X(const Y & y) :y_(y) {}    
    X(Y && y) :y_(std::move(y)) {}
};
Run Code Online (Sandbox Code Playgroud)

是否有必要像第二个那样定义构造函数以充分利用移动语义?或者在适当的情况下会自动处理?

GMa*_*ckG 7

是的,但没有.你的代码应该是这样的:

struct X
{
    Y y_;

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

如果您曾在设计中说过"我需要我自己的数据副本"*,那么您应该按值获取参数并将其移动到需要的位置.决定如何构造该值不是你的工作,这取决于该值的可用构造函数,所以让它做出选择,无论它是什么,并使用最终结果.

*当然,这也适用于功能,例如:

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));
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果某个类型是默认的可构造和可交换的(无论如何都是移动的),也会在C++ 03中应用.

// 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
    } 
};
Run Code Online (Sandbox Code Playgroud)

虽然这似乎并没有那么广泛.