c++ - (为什么)移动构造函数或移动赋值运算符应该清除它的参数吗?

我正在学习的 C++ 类(class)中的移动构造函数实现示例如下所示:

/// Move constructor
Motorcycle::Motorcycle(Motorcycle&& ori)
    : m_wheels(std::move(ori.m_wheels)),
      m_speed(ori.m_speed),
      m_direction(ori.m_direction)
{
    ori.m_wheels = array<Wheel, 2>();
    ori.m_speed      = 0.0;
    ori.m_direction  = 0.0;
}

(m_wheelsstd::array<Wheel, 2>类型的成员,Wheel只包含double m_speedbool m_rotating。在Motorcycle类中,m_speedm_direction也是double)

我不太明白为什么需要清除ori的值。

如果Motorcycle有任何我们想要“窃取”的指针成员,那么当然,我们必须设置ori.m_thingy = nullptr以免,例如delete m_thingy两次。但是,当字段包含对象本身时,这有关系吗?

我问了一位 friend ,他们将我指向this page,上面写着:

Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, moving from a std::string or from a std::vector may result in the argument being left empty. However, this behaviour should not be relied upon.

谁定义了不确定状态的含义?我看不出将速度设置为0.0比保持不变更不确定。就像引用中的最后一句话所说的那样——代码不应该依赖于从 Motorcycle 移出的状态,所以为什么还要清理它呢?

最佳答案

它们需要清洁。类的设计者认为将移动的对象零初始化是一个好主意。

请注意,确实有意义的情况是对象管理在析构函数中释放的资源。例如,指向动态分配内存的指针。不修改移出对象中的指针将意味着两个对象管理相同的资源。他们的析构函数都会尝试释放。

https://stackoverflow.com/questions/39413502/

相关文章:

c++ - 从基类构造函数调用纯虚函数

c++ - 如何在 Windows 上找到 Qt5 CMake 模块

c++ - 动态和静态范围程序差异

c++ - GCC 4.x/C++11 中的 std::string 引用计数了吗?

c++ - 虚函数默认参数行为

c++ - 库已链接,但引用未定义

c++ - C++ 标准是否对 float 的表示做了任何规定?

c++ - 持有派生类引用的基类的 std::unique_ptr 在 gcc 编译器中不显示警告,

c++ - 什么是 C++ 内联类?

c++ - 最快的素数测试算法