c++ - 是否允许将移动的对象作为 const 左值引用返回?
问题描述
是否允许将移动的值作为 const 左值引用返回?
include<string>
using namespace std;
class C {
private:
string s;
public:
const string &release() {
return move(s);
}
};
解决方案
嗯,是的,但它不会做任何事情。
该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
}
最后一个解决方案是返回一个右值引用,但我不会这样做,因为它不能保证引用被移出。
推荐阅读
- python - 灰度到 RGB 转换
- angular - 构建 Angular 7 应用程序,仅包括一些子应用程序
- javascript - 如何根据asp.net中弹出窗口的确认来决定下拉值选择
- excel - VBA 代码问题:我可以让 GoTo 成为变量吗?
- html - 如何动态发送 chrome 扩展 ID 以在网页中与 send_message 一起使用
- keras - 用于生物医学图像分割的预训练模型
- python - 如何有效地计算环形空间中的距离?
- python - 无法读取 Django FileField?
- sql - sql查询从两列匹配的表中获取多行
- matlab - MATLAB中具有初始条件的差分方程