0

After using a Move constructor in c++11, Whats the purpose of reset the pointer of the rvalue that we already steal I Mean why do we assign a nullptr to the Old Object after Stealing its content? Is it to avoid duplication of the pointer?

Auto_ptr2(Auto_ptr2& a) // note: not const
    {
        m_ptr = a.m_ptr; // transfer our dumb pointer from the source to our local object
        a.m_ptr = nullptr; // make sure the source no longer owns the pointer
    }
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
  • The purpose is not to create a [shallow copy](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy). BTW, note that `Auto_ptr2(Auto_ptr2& a)` is actually a [_copy constructor_](http://eel.is/c++draft/class.copy.ctor#1.sentence-1), and it cannot bind rvalues. – Daniel Langr Nov 22 '20 at 11:53
  • Presumably, `~Auto_ptr2` destructor runs `delete m_ptr`. Eventually, the object that `a` refers to will be destroyed. If you don't set `a.m_ptr` to null, the destructor of that object will deallocate the memory, leaving `this->m_ptr` dangling. – Igor Tandetnik Nov 22 '20 at 15:05

0 Answers0