c++ - 微软示例的这个移动构造函数似乎有冗余代码

标签 c++ c++11 move-constructor

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 1Assignment 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/

相关文章:

c++ - 将文件中的单词放入 HashMap (c++)

c++ - 使用 "new ClassType(std::move(/*class_object*/))"在 freestore 中构建对象

c++ - move 构造函数可以接受类本身以外的参数吗?

c++ - 对象指针 vector ,初始化

c++ - 在 Qt4 中创建可调整大小的侧边栏

c++ - 带开始/结束 anchor 的 CAtlRegExp 表达式问题

c++ - std::merge 不适用于 std::async

c++ - 使用索引与迭代器将 vector 迭代到倒数第二个元素

c++11 - 从参数包中的基类继承构造函数

c++ - 删除默认 C++ 复制和移动构造函数以及赋值运算符的缺点?