在这种情况下
struct Foo {};
Foo meh() {
return std::move(Foo());
}
我相信此操作是不必要的,因为新创建的 Foo
将是一个 xvalue。
但是在这种情况下呢?
struct Foo {};
Foo meh() {
Foo foo;
//do something, but knowing that foo can safely be disposed of
//but does the compiler necessarily know it?
//we may have references/pointers to foo. how could the compiler know?
return std::move(foo); //so here the move is needed, right?
}
我想那儿需要搬家,是吗?
Foo f = meh();
已经使用了(N)RVO。 - Bo Perssonstd::move
是一个标识符操作。它实际上并不执行任何操作,只是rvalue的标记。如果编译器手头有Foo
的移动构造函数,它可以看看是否有可观察的影响,并根据这个决定。如果没有可观察的影响,你怎么能区分呢? - R. Martinho Fernandesreturn
语句出现后,无论是否使用了std::move
,都不允许继续使用它们。 - user253751