【发布时间】:2017-12-05 06:58:24
【问题描述】:
开发者的MSDN page有这个代码sn-p:
// 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 1和Assignment 2的指令覆盖_data和@987654326的值时,_data(nullptr)、_length(0)有什么用@?
【问题讨论】:
-
“内存初始化”是什么意思?
-
好习惯比纳米优化更有价值。
-
@juanchopanza 在看到构造函数的左大括号之前初始化成员变量时。我不记得确切的参考,但是这个术语(mem-initializer)在流行的 C++ 文献之一中使用。内存初始化是早期 C++ 版本允许 const 和引用成员初始化的唯一方式。
-
此外,此代码调用可能引发异常的方法,这对于移动构造函数来说是一种不好的做法。
-
@SeshadriR 是的,我不认为这叫做“内存初始化”。反正代码看起来挺多余的。
标签: c++ c++11 move-constructor