【发布时间】:2011-03-08 20:54:12
【问题描述】:
我正在尝试了解 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_ 的值设置为零还是可以保持不变?不会有任何内存泄漏,也不会少一个表情。
【问题讨论】:
-
也许this answer 也有帮助...
-
我希望更正一些小细节。首先,由于此构造函数正在初始化 _data 和 _length 然后复制到它们,它应该只使用正确的值进行初始化。我不会说
other.data = NULL是“释放”,它更像是“取消设置”,没有释放内存。另外,你应该使用'nullptr'而不是'NULL',大致相同,但'nullptr'是正确的 C++。还建议避免使用std::endl,它会使您的程序在等待刷新输出时停止。除非您需要该功能,否则首选"\n"。
标签: c++ c++11 constructor move-semantics move-constructor