MSDN page for developers有以下代码片段:
// 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; }
当标记为赋值1和赋值2的指令覆盖_data和_length的值时,_data(nullptr),_ length(0)的用途是什么?
解决方法
当然应该是
// 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; }