简体   繁体   English

这个 _com_ptr_t 移动任务有什么目的吗?

[英]Is there a purpose to this _com_ptr_t move assignment?

So we have this code所以我们有这个代码

_com_ptr_t& operator=(_com_ptr_t&& cp) throw()
{
    if (m_pInterface != cp.m_pInterface) {
        Interface* pOldInterface = m_pInterface;

        m_pInterface = cp.m_pInterface;
        cp.m_pInterface = nullptr;

        if (pOldInterface != nullptr) {
            pOldInterface->Release();
        }
    }
    return *this;
}

The pOldInterface is Release()d on move assignment. pOldInterface在移动分配上是Release()d Why are move assignment/constructor operations not implemented as swaps which lets the Release() occur naturally on moved object's destructor just use the nullptr assignment or Release() to manually trigger it early?为什么移动分配/构造函数操作没有实现为交换,它让Release()在移动对象的析构函数上自然发生,只需使用nullptr分配或Release()提前手动触发它?

I always implement move constructors as swap operations.我总是将移动构造函数实现为交换操作。 Is this bad practice?这是不好的做法吗?

My code would be我的代码是

_com_ptr_t& operator=(_com_ptr_t&& cp) throw()
{
    if (m_pInterface != cp.m_pInterface) {
        Interface* pOldInterface = m_pInterface;
        m_pInterface = cp.m_pInterface;
        cp.m_pInterface = pOldInterface;
        // or just std::swap(m_pInterface, cp.m_pInterface);
    }
    return *this;
}

Is there a reasoning behind MS _com_ptr_t choice? MS _com_ptr_t选择背后有什么原因吗? This question also applies to any move assignment/constructor so this context is more/less relevant.这个问题也适用于任何移动分配/构造函数,所以这个上下文更多/更少相关。 It's all about whether we release data or we swap it?这完全取决于我们是发布数据还是交换数据?

I always implement move constructors as swap operations.我总是将移动构造函数实现为交换操作。 Is this bad practice?这是不好的做法吗?

Normally note a bad practice, but depends on what Release() does (in the first code).通常注意一个不好的做法,但取决于Release()的作用(在第一个代码中)。 If the Release() has to take care of any related objects upon Interface movements, the implementation might be different than a simple swap operation.如果Release()必须在Interface移动时处理任何相关对象,则实现可能与简单的交换操作不同。

For a trivial case, I personally prefer std::exchange idiom (need or later), which kind of make sense in the move-operations.对于一个微不足道的情况,我个人更喜欢std::exchange成语(需要或更高版本),这在移动操作中是有意义的。

_com_ptr_t& operator=(_com_ptr_t&& cp) throw()
{
    if (m_pInterface != cp.m_pInterface)
    {
        m_pInterface = std::exchange(cp.m_pInterface, nullptr);
    }
    return *this;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM