是否允许 return 移动对象作为 const 左值引用?
Is it allowed to return a moved object as a const lvalue reference?
是否允许 return 移动值作为 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`
所以它只是 return 对您传入的对象的引用。
因此,在您的代码中,您创建了一个对字符串 s
的右值引用,但将该引用绑定到 std::string const&
,无法从中移动。
你最好直接 return 参考:
const string &release() {
return s;
}
或return移动(使用交换):
std::string release() {
return std::exchange(s, std::string{});
// s valid to be reused, thanks to std::exchange
}
最后的解决方案是 return 一个右值引用,但我不会那样做,因为它不能保证引用被移动。
不,我不明白你为什么要这么做。 std::move
就像是对 rvalue-reference 类型的强制转换。从 std::move
返回的右值引用的要点是它们对应的值被有效地 移动 到另一个对象中,可能会在此过程中更改原始对象。 const 左值引用不允许您更改对象,因此无法从中移动它。
是否允许 return 移动值作为 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`
所以它只是 return 对您传入的对象的引用。
因此,在您的代码中,您创建了一个对字符串 s
的右值引用,但将该引用绑定到 std::string const&
,无法从中移动。
你最好直接 return 参考:
const string &release() {
return s;
}
或return移动(使用交换):
std::string release() {
return std::exchange(s, std::string{});
// s valid to be reused, thanks to std::exchange
}
最后的解决方案是 return 一个右值引用,但我不会那样做,因为它不能保证引用被移动。
不,我不明白你为什么要这么做。 std::move
就像是对 rvalue-reference 类型的强制转换。从 std::move
返回的右值引用的要点是它们对应的值被有效地 移动 到另一个对象中,可能会在此过程中更改原始对象。 const 左值引用不允许您更改对象,因此无法从中移动它。