3

With reference to this MSDN article , at the end (Section: Robust Programming) it states,

To prevent resource leaks, always free resources (such as memory, file handles, and sockets) in the move assignment operator.

What will happen if the move assignment is instead implemented as:

MemoryBlock& operator=(MemoryBlock&& other)
{
   if (this != &other)
   {
      std::swap(_data, other._data);
      std::swap(_length, other._length);
   }
   return *this;
}

Wouldn't the "_data" of the rvalue that "other" references be freed when it goes out of scope?

devil
  • 1,829
  • 16
  • 23
  • 1
    It will be freed if the destructor of `MemoryBlock` frees it. – kennytm Mar 16 '11 at 14:20
  • 1
    Yes the destructor in the example frees it. I am just curious about the statement in the MSDN article because swapping members seems to be a simpler way to write the move constructor and move assignment methods. But swapping will not free the memory within the move assignment. – devil Mar 17 '11 at 02:04
  • 1
    You're in fact very close to the simple method of the [copy-and-swap idiom](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom). (Note, you only need to write *one* assignment operator, not two, done right.) – GManNickG Mar 19 '11 at 20:46

1 Answers1

2

Yes, other._data will be freed when it goes out of scope (assuming a good destructor of course). However there is one item to consider: If other._data refers to a resource that needs a timely destruction, it may be destructed late in this design. An example might be the locked state of a mutex.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577