MSDN page对于开发人员有这个代码片段:
// 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;
}
当标记为Assignment 1 和Assignment 2 的指令时,_data(nullptr)
、_length(0)
有什么用 覆盖_data
和_length
的值?
最佳答案
应该是吧
// 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;
}
关于c++ - 微软示例的这个移动构造函数似乎有冗余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47647811/