最佳C++移动构造函数实现实践

Don*_*guo 4 c++ move move-constructor c++11

我试图理解move-constructor的实现.我们都知道如果我们需要管理C++类中的资源,我们需要实现五阶规则(C++编程).

微软给我们举了一个例子:https://msdn.microsoft.com/en-us/library/dd293665.aspx

这是更好的一个,它使用copy-swap来避免代码重复: 动态分配一个对象数组

     // C++11
     A(A&& src) noexcept
         : mSize(0)
         , mArray(NULL)
     {
         // Can we write src.swap(*this);
         // or (*this).swap(src);
         (*this) = std::move(src); // Implements in terms of assignment
     }
Run Code Online (Sandbox Code Playgroud)

在move-constructor中,直接:

         // Can we write src.swap(*this);
         // or (*this).swap(src);
Run Code Online (Sandbox Code Playgroud)

因为我觉得(*this) = std::move(src)有点复杂.因为如果我们(*this) = src无意中写,它会调用普通赋值运算符而不是move-assignment-operator.

除了这个问题,在微软的例子中,他们编写了这样的代码:在move-assignment-operator中,我们是否需要检查自我赋值?有可能发生吗?

// Move assignment operator.
MemoryBlock& operator=(MemoryBlock&& other)
{
   std::cout << "In operator=(MemoryBlock&&). length = " 
             << other._length << "." << std::endl;

   if (this != &other)
   {
      // Free the existing resource.
      delete[] _data;

      // Copy the data pointer and its length from the 
      // source object.
      _data = other._data;
      _length = other._length;

      // Release the data pointer from the source object so that
      // the destructor does not free the memory multiple times.
      other._data = nullptr;
      other._length = 0;
   }
   return *this;
}
Run Code Online (Sandbox Code Playgroud)

Max*_*kin 7

一种方法是实现默认构造函数,复制构造函数和swap函数.

然后使用前三个实现移动构造函数,复制和移动赋值运算符.

例如:

struct X
{
    X();
    X(X const&);
    void swap(X&) noexcept;

    X(X&& b)
        : X() // delegate to the default constructor
    {
        b.swap(*this);
    }

    // Note that this operator implements both copy and move assignments.
    // It accepts its argument by value, which invokes the appropriate (copy or move) constructor.
    X& operator=(X b) {
        b.swap(*this);
        return *this;
    }
};
Run Code Online (Sandbox Code Playgroud)

如果你一直在C++ 98中使用这个习惯用法,那么一旦你添加了移动构造函数,就可以获得移动赋值而无需编写任何代码.

在某些情况下,这个成语可能不是最有效的.因为复制操作符总是首先构造一个临时的,然后与它交换.通过手动编码赋值运算符,可以获得更好的性能.如有疑问,请检查优化的装配输出并使用分析器.


Dmy*_*nko 6

我还在互联网上寻找实现移动构造函数和移动赋值的最佳方法。有几种方法,但都不是完美的。

以下是我迄今为止的发现。

这是Test我用作示例的一个类:

class Test {
private:
  std::string name_;
  void*       handle_ = nullptr;

public:
  Test(std::string name)
    : name_(std::move(name))
    , handle_(malloc(128))
  {
  }
    
  ~Test()
  {
    if(handle_) free(handle_);
  } 

  Test(Test&& other) noexcept;             // we are going to implement it
  Test& operator=(Test&& other) noexcept;  // we are going to implement it

  void swap(Test& v) noexcept
  {
    std::swap(this->handle_, v.handle_);
    std::swap(this->name_, v.name_);
  }

private:
  friend void swap(Test& v1, Test& v2) noexcept
  {
    v1.swap(v2);
  }
};
Run Code Online (Sandbox Code Playgroud)

方法#1:直截了当

Test::Test(Test&& other) noexcept
  : handle_(std::exchange(other.handle_, nullptr))
  , name_(std::move(other.name_))
{
}

Test& Test::operator=(Test&& other) noexcept
{
  if(handle_) free(handle_);
      
  handle_ = std::exchange(other.handle_, nullptr);
  name_ = std::move(other.name_);

  return *this;
}
Run Code Online (Sandbox Code Playgroud)

优点

  • 最佳表现

缺点

  • 移动构造函数和移动赋值中的代码重复
  • 移动赋值中析构函数的代码部分重复

方法#2:破坏+建设

Test::Test(Test&& other) noexcept
  : handle_(std::exchange(other.handle_, nullptr))
  , name_(std::move(other.name_))
{
}

Test& Test::operator=(Test&& other) noexcept
{
  this->~Test();
  new (this) Test(std::move(other));

  return *this;
}
Run Code Online (Sandbox Code Playgroud)

优点

  • 无代码重复
  • 如果没有虚函数,性能良好

缺点

  • 虚拟方法表 (VMT) 初始化两次(如果类具有虚拟函数)
  • 不能在基类中使用。基类必须仅实现移动构造函数。

方法#3:复制和交换

Test::Test(Test&& other) noexcept
  : handle_(std::exchange(other.handle_, nullptr))
  , name_(std::move(other.name_))
{
}

Test& Test::operator=(Test&& other) noexcept
{
  Test (std::move(other)).swap(*this);
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

或复制和移动运算符二合一:

Test& Test::operator=(Test other) noexcept
{
  swap(other, *this);
  return *this;
}
Run Code Online (Sandbox Code Playgroud)

优点

  • 无代码重复

缺点

  • 创建了额外的对象
  • swap在函数内交换数据成员时创建的额外较小的对象
  • 交换函数中存在某种代码重复

方法#4:通过移动赋值移动构造函数

这就是你@Dongguo 在 MSDN 上找到的

Test::Test(Test&& other) noexcept
{
  *this = std::move(other);
}

Test& Test::operator=(Test&& other) noexcept
{
  if(handle_) free(handle_);
      
  handle_ = std::exchange(other.handle_, nullptr);
  name_ = std::move(other.name_);

  return *this;
}
Run Code Online (Sandbox Code Playgroud)

优点

  • 无代码重复

缺点

  • 不适用于包含非默认可构造数据成员的类。
  • 数据成员在移动构造函数中初始化两次

链接

更多答案