为什么 std::move 不会在默认移动构造函数中将源变量更改为默认值?

Vin*_*REC 2 c++ move-semantics c++11 stdmove

我试图理解移动构造函数。

我在类的构造函数中分配内存并在析构函数中销毁它。

当我尝试移动类时,我仍然有一个双空闲。

#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);
}
Run Code Online (Sandbox Code Playgroud)

为什么std::move不改为 nullptr other.a_?

如果移动构造函数是默认的,我也有同样的问题。

我发现了以下问题,但我仍然不知道为什么移动运算符不将源变量更改为默认值。

std::move 如何使原始变量的值无效?

C++如何将对象移动到nullptr

C++ std::move 一个指针

son*_*yao 6

std::move只产生一个右值(xvalue);它不会执行移动操作,它根本不会修改参数。

特别是,std::move生成一个 xvalue 表达式来标识其参数t。它完全等同于 astatic_cast到一个右值引用类型。

给定this->a_ = std::move(other.a_);,作为内置类型,即int*,this->a_只是从 复制赋值ohter.a_,那么两个指针都指向同一个对象。默认的移动构造函数实际上做同样的事情。(它对数据成员执行逐成员移动操作;请注意,对于内置类型,移动的效果与复制相同。)

如果要定义移动后对象应包含空指针,则需要显式设置other.a_为nullptr。

例如

TestClass(TestClass && other) noexcept
{
  this->a_ = other.a_;
  other.a_ = nullptr;
}
Run Code Online (Sandbox Code Playgroud)