gpt4 book ai didi

c++ - std::move 已经是 T&& 的变量

转载 作者:IT老高 更新时间:2023-10-28 22:36:47 26 4
gpt4 key购买 nike

在页面 How to: Write a Move Constructor Microsoft 有一个关于如何编写移动构造函数的示例。它本质上是这样的:

MyClass::MyClass(MyClass&& lhs)
{
*this = std::move(lhs);
}

我已经尝试过了,这里确实需要 std::move,但为什么呢?我认为 move 所做的唯一一件事就是转换为 T&&。但是 lhs 已经是 MyClass&& 类型了,不是吗?

最佳答案

Named rvalue references are lvalues. Unnamed rvalue references are rvalues. This is important to understand why the std::move call is necessary in: foo&& r = foo(); foo f = std::move(r);

看看这个答案:https://stackoverflow.com/a/5481588/1394283解释得很好。


看看这个函数:

void foo(X&& x)
{
X anotherX = x;
// ...
}

有趣的问题是:X 的复制构造函数的哪个重载在foo 的主体中被调用?这里,x 是一个声明为右值引用的变量。因此,期望 x 本身也应该像右值一样绑定(bind)是很合理的,也就是说,X(X&& rhs); 应该被调用。

允许将移动语义默认应用于具有名称的事物,如

X anotherX = x;
// x is still in scope!

这将是危险的困惑和容易出错,因为我们刚刚移动的东西,即我们刚刚窃取的东西,仍然可以在后续代码行中访问。 但移动语义的全部意义在于仅将其应用于“无关紧要”的地方,即我们从中移动的东西在移动后立即死亡并消失。

这就是为什么右值引用的设计者选择了一个比这更微妙的解决方案:

Things that are declared as rvalue reference can be lvalues or rvalues. The distinguishing criterion is: if it has a name, then it is an lvalue. Otherwise, it is an rvalue.

来源:http://thbecker.net/articles/rvalue_references/section_05.html

关于c++ - std::move 已经是 T&& 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17949383/

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