移动构造函数/ operator = [英] Move constructor/operator=

查看:217
本文介绍了移动构造函数/ operator =的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to learn about new feature of C++ namely move constructor and assignment X::operator=(X&&) and I found interesting example but the only thing I quite not even understand but more dissagree is one line in move ctor and assignment operator (marked in the code below):

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.
}



因此我的问题是:我必须将lenght_的值设置为零或者我可以保持不变?

So my question is: do I have to set the value of lenght_ to zero or can I leave it untouched? There won't be any memory-leak and one expression less afaics.

推荐答案

因为move from对象还在进行,所以不会有任何内存泄漏和一个表达式最终被破坏,所以你必须将它保持在一致的状态。当然,这样做的确切方式取决于你的对象,在这种情况下,它显然意味着将数据指针置零,并将长度设置为零。

Because the "moved from" object is still going to be destructed eventually, so you have to leave it in a consistent state. Exactly how you do this depends on your object, of course, and in this case it apparently means nulling out the data pointer and setting the length to zero.

这篇关于移动构造函数/ operator =的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆