这段代码合法吗? (C++0x 移动语义)
我很好奇这段代码在 C++0x 中是否合法。具体来说,函数 move_it()
中声明的对象是否会正确移动到 main()
中声明的对象?
#include <iostream>
#include <string>
#include <tr1/memory>
using namespace std;
class x
{
public:
x() { cout << "create " << this << endl; }
~x() { cout << "destroy " << this << endl; }
};
x&& move_it()
{
x r;
return move(r);
}
int main()
{
x n = move_it();
return 0;
}
I'm curious as to whether this code is legal in C++0x. Specifically, will the object declared in the function move_it()
be properly moved to the object declared in main()
?
#include <iostream>
#include <string>
#include <tr1/memory>
using namespace std;
class x
{
public:
x() { cout << "create " << this << endl; }
~x() { cout << "destroy " << this << endl; }
};
x&& move_it()
{
x r;
return move(r);
}
int main()
{
x n = move_it();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,它返回对本地对象的引用,就像左值引用一样。
只需按值返回它,然后让 x 假定的移动构造函数获取右值。当按值返回时,返回的对象是右值。
如果幸运的话,NRVO 优化将会启动(就像以前一样)并消除复制。
No, it is returning a reference to a local object, just like with an lvalue reference.
Just return it by value and let x's assumed move constructor pick up the rvalue. When you return by value, the returned object is an rvalue.
If you are lucky, the NRVO optimization will kick in (just like before) and elide the copying anyway.
您将从
move_it
返回一个悬空右值引用,当您在main
中访问它时,它会调用未定义的行为。如果要移动对象,请将返回类型更改为 x 并取消移动:(
从函数返回时,自动变量被隐式视为右值。)
You are returning a dangling rvalue reference from
move_it
, which invokes undefined behavior when you access it inmain
.If you want to move the object, change the return type to
x
and get rid of the move:(Automatic variables are implicitly treated as rvalues when returned from a function.)
作为普通用户,任何不实现模板库的人,您应该使用右值引用的唯一用途是实现移动构造函数和移动分配。
观看此视频 http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-9-of-n
As a regular user, anyone not implementing a template library, the only use for r-value references you should make is in implementing move constructors and move assignment.
Check out this video http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-9-of-n