dem*_*emi 10 c++ rvalue-reference c++11
关于C++右值引用的Artima文章(http://www.artima.com/cppsource/rvalue.html)有一些词:这就是为什么在传递给基类时有必要说move(x)而不是x .这是移动语义的一个关键安全功能,旨在防止意外地从某个命名变量移动两次.
当这样的双重动作可以执行时,我无法想到情况.你能举个例子吗?换句话说,如果所有成员T&&
都是rvalue引用而不仅仅是引用会出什么问题?
GMa*_*ckG 16
考虑这种情况:
void foo(std::string x) {}
void bar(std::string y) {}
void test(std::string&& str)
{
// to be determined
}
Run Code Online (Sandbox Code Playgroud)
我们想打电话foo
跟str
,然后bar
用str
,既具有相同的值.最好的方法是:
foo(str); // copy str to x
bar(std::move(str)); // move str to y; we move it because we're done with it
Run Code Online (Sandbox Code Playgroud)
这样做是错误的:
foo(std::move(str)); // move str to x
bar(std::move(str)); // move str to y...er, except now it's empty
Run Code Online (Sandbox Code Playgroud)
因为在第一次移动之后,值str
未指定.
因此在rvalue引用的设计中,这种隐式移动并不存在.如果是的话,我们上面最好的方法是行不通的,因为首先提到的str
是std::move(str)
相反的.
归档时间: |
|
查看次数: |
336 次 |
最近记录: |