C++ C++;11移动语义以防止从调用方转移res的所有权 模板 班级成绩{ ... /** *将基础结果强制转换为r值,以便调用者无法获得基础资源的所有权。 *当涉及到流时,这是必要的。 */ 内联R&&GetResultWithOwnership() { 返回std::移动(结果); } 内联常量E&GetError()常量 { 返回误差; } 内联布尔IsSuccess()常量 { 返回此->成功; } 私人: R结果; E误差; 成功; };
基于上面的代码,getter返回了私有成员的右值引用,std::move是否使资源窃取成为可能?为什么评论说呼叫方不能取得所有权?可能是输入错误。评论似乎与代码不符。可能是输入错误。评论似乎与代码不符。C++ C++;11移动语义以防止从调用方转移res的所有权 模板 班级成绩{ ... /** *将基础结果强制转换为r值,以便调用者无法获得基础资源的所有权。 *当涉及到流时,这是必要的。 */ 内联R&&GetResultWithOwnership() { 返回std::移动(结果); } 内联常量E&GetError()常量 { 返回误差; } 内联布尔IsSuccess()常量 { 返回此->成功; } 私人: R结果; E误差; 成功; };,c++,c++11,std,move,C++,C++11,Std,Move,基于上面的代码,getter返回了私有成员的右值引用,std::move是否使资源窃取成为可能?为什么评论说呼叫方不能取得所有权?可能是输入错误。评论似乎与代码不符。可能是输入错误。评论似乎与代码不符。 template<typename R, typename E> class Outcome { ... /**
template<typename R, typename E>
class Outcome {
...
/**
* casts the underlying result to an r-value so that caller can't take ownership of underlying resources.
* this is necessary when streams are involved.
*/
inline R&& GetResultWithOwnership()
{
return std::move(result);
}
inline const E& GetError() const
{
return error;
}
inline bool IsSuccess() const
{
return this->success;
}
private:
R result;
E error;
bool success;
};