Providing correct move semantics

后端 未结 1 653
再見小時候
再見小時候 2021-01-05 13:02

I am currently trying to figure out how to do move semantics correctly with an object which contains a pointer to allocated memory. I have a big datastructure, which contain

相关标签:
1条回答
  • 2021-01-05 13:31

    "Moving" a pointer is no different than copying one and does not set the moved-from value to null ('moving' is in quotes here because std::move does not move anything really, it just changes the value category of the argument). Just copy rhs' pointer then set it to nullptr:

    struct structure
    {
        structure()
          : m_data{new big_and_complicated{}}
        { }
    
        structure(structure&& rhs)
          : m_data{rhs.m_data}
        {
            rhs.m_data = nullptr;
        }
    
        structure& operator =(structure&& rhs)
        {
            if (this != &rhs)
            {
                delete m_data;
                m_data = rhs.m_data;
                rhs.m_data = nullptr;
            }
            return *this;
        }
    
        ~structure()
        {
            delete m_data;
        }
    
    private:
        big_and_complicated* m_data;
    
        structure(structure const&) = delete;             // for exposition only
        structure& operator =(structure const&) = delete; // for exposition only
    }
    

    Better yet, use std::unique_ptr<big_and_complicated> instead of big_and_complicated* and you don't need to define any of this yourself:

    #include <memory>
    
    struct structure
    {
        structure()
          : m_data{new big_and_complicated{}}
        { }
    
    private:
        std::unique_ptr<big_and_complicated> m_data;
    }
    

    Lastly, unless you actually want structure to remain non-copyable, you're better off just implementing proper move semantics inside of big_and_complicated and having structure hold a big_and_complicated object directly.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题