问题描述
关于C ++右值参考的Artima文章()有词语:这就是为什么当向下传递给基类时,需要说move(x)而不是x。这是移动语义的一个关键安全特性,旨在防止意外地从某个命名变量移动两次。
On Artima article about C++ rvalue reference (http://www.artima.com/cppsource/rvalue.html) there is words: That's why it is necessary to say move(x) instead of just x when passing down to the base class. This is a key safety feature of move semantics designed to prevent accidently moving twice from some named variable.
执行。你能举个例子吗?换句话说,如果 T&&
的所有成员都是右值引用而不仅仅是引用,那么会出错?
I can't think situation when such double move can perform. Can you give an example of this? In other words, what will go wrong if all members of T&&
would be rvalue references and not just references?
推荐答案
请考虑这种情况:
void foo(std::string x) {}
void bar(std::string y) {}
void test(std::string&& str)
{
// to be determined
}
我们要调用 foo
str
, bar
两者具有相同的值。最好的方法是:
We want to call foo
with str
, then bar
with str
, both with the same value. The best way to do this is:
foo(str); // copy str to x
bar(std::move(str)); // move str to y; we move it because we're done with it
这样做是错误的: p>
It would be a mistake to do this:
foo(std::move(str)); // move str to x
bar(std::move(str)); // move str to y...er, except now it's empty
str
的值未指定。
因此在右值引用的设计中,隐式移动不存在。如果是,我们最好的方法不会工作,因为 str
的第一次提及将是 std :: move(str)
。
So in the design of rvalue references, this implicit move is not there. If it were, our best way above would not work because the first mention of str
would be std::move(str)
instead.
这篇关于Rvalue引用:为什么不会隐式移动右值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!