【发布时间】:2020-08-28 14:42:15
【问题描述】:
我尝试理解移动构造函数。
我在类的构造函数中分配内存并在析构函数中销毁它。
当我尝试移动班级时,我仍然有双倍免费。
#include <algorithm>
class TestClass
{
public:
TestClass() {a_ = new int[1];}
TestClass(TestClass const& other) = delete;
TestClass(TestClass && other) noexcept // = default;
{
this->a_ = std::move(other.a_);
}
~TestClass() {delete[] a_;}
private:
int* a_ = nullptr;
};
int main( int argc, char** argv )
{
TestClass t;
TestClass t2 = std::move(t);
}
为什么std::move不改成nullptr other.a_?
如果移动构造函数是默认的,我也会遇到同样的问题。
我找到了以下问题,但我仍然不知道为什么移动运算符不将源变量更改为默认值。
How does std::move invalidates the value of original variable?
【问题讨论】:
-
在你的移动构造函数中,你忘记了
other.a_ = nullptr;。或者通过std::swap(this_>a_, other.a_);. -
在 C++14 及更高版本中,您将使用
std::exchange来初始化a_ -
我认为这是某种培训,这就是为什么您不使用
std::vector,它会以最好的方式做到这一点。 -
是的,它是 POC。我想了解移动构造函数/赋值的默认实现是什么,并知道何时需要使用默认或自定义实现。
-
@VincentLEGARREC
std::move()只是一个类型转换,您试图“移动”到原始指针,而不是使用移动构造函数或移动赋值运算符的可移动类型。这实际上是一个复制分配,因此没有调用代码来实际将输入指针重置为nullptr。
标签: c++ c++11 move-semantics stdmove