Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 这次搬家任务有什么目的吗?_C++_Oop_C++11_Swap_Move Semantics_C++14 - Fatal编程技术网

C++ 这次搬家任务有什么目的吗?

C++ 这次搬家任务有什么目的吗?,c++,oop,c++11,swap,move-semantics,c++14,C++,Oop,C++11,Swap,Move Semantics,C++14,所以我们有这个代码 _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

所以我们有这个代码

_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;
}
pOldInterface
Release()d
移动分配。为什么移动赋值/构造函数操作不作为交换来实现,从而让
Release()
在移动对象的析构函数上自然发生,只需使用
nullptr
赋值或
Release()
手动提前触发它

我总是将移动构造函数实现为交换操作。这是坏习惯吗

我的密码是

_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;
}
MS
\u com\u ptr\t
选择背后有什么原因吗?此问题也适用于任何移动分配/构造函数,因此此上下文或多或少相关。关键在于我们是发布数据还是交换数据

我总是将移动构造函数实现为交换操作。这不好吗 练习

通常会注意到一种不好的做法,但这取决于
Release()
的作用(在第一个代码中)。如果
Release()
必须在
接口
移动时处理任何相关对象,则实现可能不同于简单的交换操作

对于一个简单的例子,我个人更喜欢成语(need或更高版本),它在移动操作中是有意义的

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

C++ COM对象只是一个围绕C API的薄薄包装,它不知道C++的值或移动语义。@ COM部分的程序员是不相关的。许多开发人员在移动时甚至为非com对象发布分配/构造,而不是在资源可交换时仅交换资源。这不是一般性的东西或任何东西,而是取决于每个库或(非com)接口规范的实现细节。您必须始终执行文档指定的操作。无论如何,如果结构没有实现移动语义或交换,您需要在代码中自行处理,编译器无法为您创建此类代码。