【发布时间】:2014-02-13 05:28:23
【问题描述】:
假设我有一个类,其内部数据表示例如是std::string:
class my_type {
std::string m_value;
...
};
如果我可以“移出”my_type 的内部表示会很好吗?这种能力将以如下方式完成:
class my_type {
std::string m_value;
public:
operator std::string() && {
// NOTE: ^^ ref qualifier for r-value
return std::move(m_value);
// Explicitly do std::move is used because ref-qualifiers don't apply
// to data members (m_value would still be an l-value), and (N)RVO
// would be crazy for the compiler to apply here.
}
};
...
my_type val;
std::string str1 = std::move(val);
std::string str2 = a_func_that_returns_my_type();
具体问题:
移出内部表示是 BadIdea™ 吗? (例如泄漏的实现?)
-
我是否在滥用(隐式)转换运算符?如果是这样,我应该使用明确的吗?示例:
std::string str = std::move(val).get_str(); // Or auto instead of explicit std::string // Is this a GoodIdea™?或
auto str = val.move_str_out(); 是否应该仅在存在用于左值的转换运算符/函数时才定义它?
我在这里尝试实现的目标是否被视为过早优化?
有关一些背景信息,请参阅:
-
What is "rvalue reference for *this"?(用于
&&ref-qualifer) - Overload resolution with ref-qualifiers(此处显示与我的代码类似的模式)
【问题讨论】:
-
“我在这里尝试实现的目标是否被视为过早优化?” “优化”是什么意思?您没有指定要优化的潜在缓慢方案。什么是缓慢的替代方案?
-
在字符串被
moved out 之后,你的对象会出现段错误吗?
标签: c++ c++11 move-semantics