gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:22:10 25 4
gpt4 key购买 nike

考虑以下几点:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com