为什么要在移动构造函数的末尾将基元类型值设置为零
Why set primitive type value to zero in the end of move constructor function
MemoryBlock(MemoryBlock&& other)
: _data(nullptr)
, _length(0)
{
std::cout << "In MemoryBlock(MemoryBlock&&). length = "
<< other._length << ". Moving resource." << std::endl;
_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;
}
下面是来自 Microsoft msdn 的示例。它size_t,不可能是免费的。因此,您不必将其分配给 0。为什么将other._length设置为 0?感谢
为了完整起见,据我所知没有具体的技术原因。 other
在退出其作用域时将被销毁,因为您在 move 构造函数中将其定义为右值引用。
您必须确保将移动构造函数/赋值中的右值引用保留为可破坏状态,这是通过将nullptr
分配给_data
的情况(通常必须确保指针指向null
(。_length = 0
只是为了完整性(或习惯(:移动数据,数据指针为空,长度必须为零。
这样做通常是一个好主意,这样您就可以保持更严格的不变量,使类的其他部分更容易推理,并且需要更少的 if 检查。举一个具体的例子,假设 MemoryBlock 有一个返回 length 的 length(( 方法。如果您没有在移动时设置_length,则此 length(( 方法将需要 if 检查_data不为 null。通过在移动后将其设置为零,此方法可以简单地返回_length。
将对象 A 的内容移动到另一个对象 B 后,A 仍然存在。 它将在范围结束时被销毁,同时可以再次使用。 你不能真正指望 A 的内容在被移动后是什么,但你可以给它分配一个新值。 例如,这是合法代码:
std::string a = "Some string";
std::cout << "a before move: " << a << endl;
std::string b = std::move(a);
std::cout << "a after move: " << a << endl;
std::cout << "b after move: " << b << endl;
a = "Some other string";
std::cout << "a after reassignment: " << a << endl;
它在Visual Studio下生成以下内容:
a before move: Some string
a after move:
b after move: Some string
a after reassignment: Some other string
相关文章:
- C++(和 ROS) - 包含与前向声明引用,设置默认值和类型定义
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- Poco 库 PUT 方法未按预期工作,尽管主机、方法、内容类型设置正确
- 无法在 HEVC 解码器上设置输出类型 IMFTransform
- Visual Studio 2019 - 设置文件类型的默认扩展名
- 无法在VSCode中设置C++调试;无法识别调试类型
- 将变量设置为类型模板
- 在 C++ 中设置的用户定义数据类型
- 为自定义路径类型设置提升property_tree
- C++:无法在按位函数后将 int 类型设置为非标量
- 为什么我不能为位于基类中的类中的类型设置别名
- 可以将枚举的默认类型设置为无符号字符
- 有没有办法使用显式实例化按类型设置成员变量
- C++中用于将默认变量类型设置为int的任何选项
- 是否可以继承模板类并将类型设置为当前尝试从中继承的类的模板化子类?
- 如何使用 std::conditional 根据模板参数类型设置类型
- 事件类型设置为SDL_MOUSEBUTTONDOWN,即使在未按下任何按钮时也是如此
- std::使用自定义类型设置差异
- 为具有多重继承的一个类型设置默认构造函数
- 如何为特定的模板数据类型设置条件