首页 > 解决方案 > 是否允许将移动的对象作为 const 左值引用返回?

问题描述

是否允许将移动的值作为 const 左值引用返回?

include<string>
using namespace std;

class C {
private:
  string s;
public:
  const string &release() {
    return move(s);
  }
};

标签: c++move

解决方案


嗯,是的,但它不会做任何事情。

std::move函数只是对右值引用的强制转换。所以实际上:

std::string s;
std::move(s); // returns std::string&& to `s`

所以它只是返回对你传入的对象的引用。

因此,在您的代码中,您创建了一个对您的 string 的右值引用s,但是您将该引用绑定到 a std::string const&,它不能被移动。

您最好直接返回参考:

const string &release() {
    return s;
}

或通过移动返回(使用交换):

std::string release() {
    return std::exchange(s, std::string{});
    // s valid to be reused, thanks to std::exchange
}

最后一个解决方案是返回一个右值引用,但我不会这样做,因为它不能保证引用被移出。


推荐阅读