在移动赋值运算符中使用std :: swap重用析构函数逻辑是否有意义? [英] Does it make sense to reuse destructor logic by using std::swap in a move assignment operator?

查看:213
本文介绍了在移动赋值运算符中使用std :: swap重用析构函数逻辑是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

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;
    }
};

我的想法是,析构函数将很快在其他上运行,不得不通过使用交换在移动赋值运算符中再次实现我的析构逻辑。但我不确定这是一个合理的假设。这将是好的?

My thinking here is that the destructor will be running on "other" shortly, and as such I don't have to implement my destructor logic again in the move assignment operator by using swap. But I'm not sure that's a reasonable assumption. Would this be "okay"?

推荐答案

这应该是确定,但它几乎不比推荐的传值方法,在这种情况下,移动构造函数将用于这种情况。

It should be ok, but it's scarcely any better than the recommended technique of pass-by-value, in which case the move constructor would be used in this situation.

这篇关于在移动赋值运算符中使用std :: swap重用析构函数逻辑是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆