在C++中,需要移动构造函数来重置已移动的对象,在我看来,这似乎是大多数情况下析构函数所做的重复。
定义复位方法并在析构函数和移动构造函数中使用它是最佳方法是否正确?还是有更好的方法?
最佳答案
is required to reset the moved object which to me seems to be a duplication of what the destructor does in most of the cases.
在我看来,您大多数情况下都会误解析构函数的用途。
移动中“重置”(如您所称)的目的是设置对象的状态,使其满足析构函数的内部前提条件(更一般地,任何类不变式)。如果构造函数不这样做,则该对象将无法销毁,这将违反约定和良好实践,并可能导致错误。
在许多情况下,析构函数可能无法执行相同的“重置”操作。例如,无法将无效指针与有效指针区分开。这就是为什么智能指针的move构造函数将指针重置为null的原因。
Is it correct that defining a reset-method and using it in both destructor and move-constructor is the best approach?
目前尚不清楚这何时会有用。似乎并不典型。
关于c++ - 重置 move 对象的常用惯用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63661319/