【发布时间】:2016-04-20 11:22:35
【问题描述】:
我刚刚从https://msdn.microsoft.com/en-us/library/dd293665.aspx 发现了以下代码,它显示了如何实现移动 ctor:
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 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 = nullptr;
other._length = 0;
}
此代码附带的问题/疑问之一是:如果类 MemoryBlock 包含一些类类型成员变量(比如 someclassvar ),并且如果该成员相当大,那么下面的行会在修改后的move ctor有效(假设这个someclassvar没有move ctor)?
MemoryBlock(MemoryBlock&& other)
: _data(nullptr)
, _length(0),someclassvar(other.someclassvar)
{
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;
// someclassvar=other.someclassvar;
// 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;
delete other.someclassvar;
}
这里someclassvar = other.someclassvar; 我相信这会调用复制赋值运算符,那么这种行为有效吗?此外,如果someclassvar 包含移动分配和复制分配,可以预期调用哪个?
move ctor 在所有情况下都有效吗?如果没有,是否有副本 ctor 更好?
【问题讨论】:
-
someclassvar = std::move(other.someclassvar); -
(assumed that this someclassvar doesn't have move ctor)有 std::move 做这项工作吗? -
没有。
std::move将move如果move ctor / move =可用,否则copy -
首先,Move 并没有真正移动,它只是无条件地将参数转换为移动 ctor 将接受的右值,我的问题是我构造的移动 ctor 在所有情况下都有效吗?
-
如您所见,
someclassvar(可能)是某个指针,因此有问题的行将是一个指针分配。
标签: c++ move-semantics