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
?
No move constructor is automatically generated.
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.
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With