c – Microsoft示例的此移动构造函数似乎具有冗余代码

前端之家收集整理的这篇文章主要介绍了c – Microsoft示例的此移动构造函数似乎具有冗余代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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;  
}
原文链接:https://www.f2er.com/c/117869.html

猜你在找的C&C++相关文章