在以下 C++11+ 代码中,应该首选哪个 return 语句构造?
#include <utility>
struct Bar
{
};
struct Foo
{
Bar bar;
Bar get() &&
{
return std::move(bar); // 1
return bar; // 2
}
};
最佳答案
好吧,既然它是一个 r-value ref 限定的成员函数,this
大概就要过期了。因此,将 bar
移出是有意义的,假设 Bar
实际上从被 move 中获得了一些东西。
由于 bar
是一个成员,而不是本地对象/函数参数,因此在 return 语句中复制省略的常用标准不适用。除非您明确地 std::move
它,否则它将始终复制。
所以我的答案是选择第一个选项。
关于c++ - 从 r-value ref-qualified 方法 move 还是不 move ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485885/