Bil*_*eal 2 c++ move-semantics c++11 move-assignment-operator
考虑以下:
class Example : boost::noncopyable
{
HANDLE hExample;
public:
Example()
{
hExample = InitializeHandle();
}
~Example()
{
if (hExample == INVALID_HANDLE_VALUE)
{
return;
}
FreeHandle(hExample);
}
Example(Example && other)
: hExample(other.hExample)
{
other.hExample = INVALID_HANDLE_VALUE;
}
Example& operator=(Example &&other)
{
std::swap(hExample, other.hExample); //?
return *this;
}
};
Run Code Online (Sandbox Code Playgroud)
我的想法是析构函数将很快在"其他"上运行,因此我不必通过使用swap在移动赋值运算符中再次实现我的析构函数逻辑.但我不确定这是一个合理的假设.这会"好"吗?
想象一下:
// global variables
Example foo;
struct bar {
void f() {
x = std::move(foo); // the old x will now live forever
}
Example x;
}
Run Code Online (Sandbox Code Playgroud)
类似的习惯用法,复制和交换(或者在这种情况下,移动和交换)确保析构函数立即运行,我相信这是一个更好的语义.
Example& operator=(Example other) // other will be moved here
{
std::swap(hExample, other.hExample);
return *this;
} // and destroyed here, after swapping
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
467 次 |
| 最近记录: |