我想了解C++的新功能,即移动构造函数和赋值X::operator=(X&&)
,我发现interesting example,但我唯一不甚了解,但更不同意的是移动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.
}
所以我的问题是:我必须lenght_的值设置为零或我可以离开它不变?不会有任何内存泄漏,并且一个表达式不会有任何缺陷。
也许[这个答案](http://stackoverflow.com/questions/3106110/can-someone-please-explain-move-semantics-to-me/3109981#3109981)也有帮助... – fredoverflow 2010-06-27 20:49:16
几个小细节我想纠正。首先,由于此构造函数正在初始化_data和_length,然后复制到它们,它应该只用正确的值进行初始化。 我不会说'其他。data = NULL'就是'释放',它更像'unsetting',没有释放内存。 此外,你应该使用'nullptr'而不是'NULL',大致相同,但是'nullptr'是*正确的* C++。 避免使用'std :: endl'也是可取的,它会让程序在等待输出被刷新时停下来。除非你需要这个功能,否则更喜欢'“\ n”'。 – thecoshman 2013-07-02 13:50:18