Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This move constructor of Microsoft example appears to have redundant code

The MSDN page for developers has this code snippet:

// Move constructor.  
MemoryBlock(MemoryBlock&& other) : _data(nullptr), _length(0)  
{  
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "   
             << other._length << ". Moving resource." << std::endl;  

   // Copy the data pointer and its length from source object.  
   _data = other._data;      // Assginment 1
   _length = other._length;  // Assignment 2

   // Release the data pointer from the source object so that  
   // the destructor does not free the memory multiple times.  
   other._data = nullptr;  
   other._length = 0;  
}

What's the use of _data(nullptr), _length(0), when the instructions labelled Assignment 1 and Assignment 2 over-write the values of _data and _length?

like image 477
Seshadri R Avatar asked Dec 05 '17 06:12

Seshadri R


People also ask

Is move constructor automatically generated?

No move constructor is automatically generated.

What is move constructor and assignment operator?

The move assignment operator is different than a move constructor because a move assignment operator is called on an existing object, while a move constructor is called on an object created by the operation. Thereafter, the other object's data is no longer valid.

Is implicitly declared as deleted?

The implicitly-declared or defaulted copy assignment operator for class T is defined as deleted in any of the following is true: T has a non-static data member that is const. T has a non-static data member of a reference type.


2 Answers

Surely it should be

// Move constructor.  
MemoryBlock(MemoryBlock&& other) : _data(other._data), _length(other._length)
{  
   std::cout << "In MemoryBlock(MemoryBlock&&). length = "   
             << other._length << ". Moving resource." << std::endl;  

   // Release the data pointer from the source object so that  
   // the destructor does not free the memory multiple times.  
   other._data = nullptr;  
   other._length = 0;  
}  
like image 86
SJHowe Avatar answered Oct 18 '22 08:10

SJHowe


For safety.

Let's say that for some reason, other._data and/or other._length fail to access their value (most probably the pointer other._data though).

An example could be that the pointer is pointing to invalid memory and produce a Segmentation Fault (since you may access memory that is not own by your program), and the program to crash at that point. Another possibility is that other is *nullptr, and so on... What are the values of _data and _length then? Undefined.

It would be nice for these two to have their initial value, since that might help debugging, since the programmer can think that since these two have their initial values, maybe there is something wrong in the assignment.

like image 42
gsamaras Avatar answered Oct 18 '22 06:10

gsamaras