移动构造函数/运算符=

The*_* do -1 c++ constructor move-constructor move-semantics c++11

我正在尝试学习C++的新功能,即移动构造函数和赋值X::operator=(X&&),我发现了一些有趣的例子, 但我唯一不理解但更不同意的是移动ctor和赋值运算符中的一行(在下面的代码中标记):

MemoryBlock(MemoryBlock&& other)
   : _data(NULL)
   , _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = " 
             << other._length << ". Moving resource." << std::endl;

   // Copy the data pointer and its length from the 
   // source object.
   _data = other._data;
   _length = other._length;

   // Release the data pointer from the source object so that
   // the destructor does not free the memory multiple times.
   other._data = NULL;
   other._length = 0;//WHY WOULD I EVEN BOTHER TO SET IT TO ZERO? IT DOESN'T MATTER IF IT'S ZERO OR ANYTHING ELSE IT IS JUST A VALUE.
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:我是否必须将lenght_的值设置为零,还是可以保持不变?不会有任何内存泄漏和一个表达减少afaics.

Ter*_*fey 6

因为"移动"对象最终仍将被破坏,所以你必须将它保持在一致的状态.当然,具体如何执行此操作取决于您的对象,在这种情况下,它显然意味着将数据指针置零并将长度设置为零.

  • 令人难以置信的是,人们会提出正确的答案.什么傲慢. (4认同)