我正在学习的 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_wheels
是std::array<Wheel, 2>
类型的成员,Wheel只包含double m_speed
和bool m_rotating
。在Motorcycle类中,m_speed
和m_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 astd::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/