在移动赋值运算符中使用std :: swap重用析构函数逻辑是否有意义?

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在移动赋值运算符中再次实现我的析构函数逻辑.但我不确定这是一个合理的假设.这会"好"吗?

R. *_*des 8

想象一下:

// 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)

  • 如果对象不可移动,则编译器尝试复制时将生成编译器错误. (2认同)

Ben*_*igt 5

它应该没问题,但它几乎没有推荐的pass-by-value技术,在这种情况下,移动构造函数将被用于这种情况.

  • @Ben:在`swap`里面. (2认同)