c++ - 是否有必要定义来自不同类的 move 构造函数?

标签 c++ c++11 rvalue-reference move-semantics

考虑以下几点:

struct X
{
    Y y_;

    X(const Y & y) :y_(y) {}    
    X(Y && y) :y_(std::move(y)) {}
};

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

最佳答案

是的,但不是。你的代码应该是这样的:

struct X
{
    Y y_;

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

如果您在设计中说过“我需要我自己的数据拷贝”*,那么您应该按值获取参数并将其 move 到需要的位置。决定如何构造该值不是您的工作,这取决于该值的可用构造函数,所以让它做出选择,无论它是什么,并处理最终结果。

*这当然也适用于函数,例如:

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));
}

请注意,如果一个类型是默认可构造和可交换的(无论如何都是 move 的),则在某种程度上也适用于 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
    } 
};

虽然这似乎没有被广泛采用。

关于c++ - 是否有必要定义来自不同类的 move 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4839257/

相关文章:

c++ - 我应该返回一个右值引用(通过 std::move'ing)吗?

c++11 - 引用折叠规则是否适用于返回类型?

c++ - 在 C++ 中链接对临时对象的调用

c++ - 什么是 16 字节有符号整数数据类型?”

c++ - 如何让 Windows 10 Game Bar 出现在游戏中?

c++ - 最多打印 4 位小数

linux - CMake 3.15.5 Bootstrap 因 g++ 9.3.0 而失败

c++ - 打印单个字符的合适方法是什么?

c++ - 互斥保护 block 中的同步模式

c++ - 为什么c++没有默认初始化