如何:编写一个移动构造函数

本主题介绍如何编写移动构造函数和 C++ 类移动赋值运算符。 移动构造函数使您能够实施移动语义,这可以显著提高应用程序性能。 有关移动语义的详细信息,请参阅Rvalue引用声明:&&

本主题基于下面的 C++ 类, MemoryBlock,它管理的内存缓冲区。

// MemoryBlock.h
#pragma once
#include <iostream>
#include <algorithm>

class MemoryBlock
{
public:

   // Simple constructor that initializes the resource.
   explicit MemoryBlock(size_t length)
      : _length(length)
      , _data(new int[length])
   {
      std::cout << "In MemoryBlock(size_t). length = "
                << _length << "." << std::endl;
   }

   // Destructor.
   ~MemoryBlock()
   {
      std::cout << "In ~MemoryBlock(). length = "
                << _length << ".";
      
      if (_data != NULL)
      {
         std::cout << " Deleting resource.";
         // Delete the resource.
         delete[] _data;
      }

      std::cout << std::endl;
   }

   // Copy constructor.
   MemoryBlock(const MemoryBlock& other)
      : _length(other._length)
      , _data(new int[other._length])
   {
      std::cout << "In MemoryBlock(const MemoryBlock&). length = " 
                << other._length << ". Copying resource." << std::endl;

      std::copy(other._data, other._data + _length, _data);
   }

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

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

         _length = other._length;
         _data = new int[_length];
         std::copy(other._data, other._data + _length, _data);
      }
      return *this;
   }

   // Retrieves the length of the data resource.
   size_t Length() const
   {
      return _length;
   }

private:
   size_t _length; // The length of the resource.
   int* _data; // The resource.
};

下面的过程描述如何编写移动赋值运算符,例如 C++ 类,移动构造函数。

若要创建移动 C++ 类的构造函数

  1. 定义一个空构造函数方法,即采用的类类型 rvalue 引用作为参数,如下面的示例所示):

    MemoryBlock(MemoryBlock&& other)
       : _data(NULL)
       , _length(0)
    {
    }
    
  2. 在移动构造函数中,分配从源对象类的数据成员的对象的构造:

    _data = other._data;
    _length = other._length;
    
  3. 将源对象的数据成员指定为默认值。 这样可以防止该析构函数释放资源 (如内存) 的多个时间:

    other._data = NULL;
    other._length = 0;
    

若要创建 C++ 类移动赋值运算符

  1. 定义空赋值运算符,作为其参数的类类型 rvalue 引用,并返回引用的类类型,如下面的示例所示:

    MemoryBlock& operator=(MemoryBlock&& other)
    {
    }
    
  2. 在移动赋值运算符,将添加不执行任何操作,如果您尝试将对象分配给自己的条件语句。

    if (this != &other)
    {
    }
    
  3. 在条件语句中,请从分配给对象释放任何资源 (如内存)。

    下面的示例可以释放_data分配给该对象中的成员:

    // Free the existing resource.
    delete[] _data;
    

    请按照步骤 2 和步骤 3 中传输的数据成员的源对象构造的对象的第一个步骤操作:

    // 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 = NULL;
    other._length = 0;
    
  4. 返回当前的对象的引用,如下面的示例中所示:

    return *this;
    

示例

下面的示例显示了完整的移动构造函数和移动赋值运算符为MemoryBlock类:

// Move constructor.
MemoryBlock(MemoryBlock&& other)
   : _data(NULL)
   , _length(0)
{
   std::cout << "In MemoryBlock(MemoryBlock&&). length = " 
             << other._length << ". Moving resource." << std::endl;

   // 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 = NULL;
   other._length = 0;
}

// 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 = NULL;
      other._length = 0;
   }
   return *this;
}

下面的示例演示如何移动语义可以提高您的应用程序的性能。 本示例将两个元素添加到矢量对象,然后插入新元素之间的两个现有元素。 在Visual C++ 2010、 vector类使用移动可以高效地移动 (而不是将其复制的向量的元素执行的插入操作的语义。

// rvalue-references-move-semantics.cpp
// compile with: /EHsc
#include "MemoryBlock.h"
#include <vector>

using namespace std;

int main()
{
   // Create a vector object and add a few elements to it.
   vector<MemoryBlock> v;
   v.push_back(MemoryBlock(25));
   v.push_back(MemoryBlock(75));

   // Insert a new element into the second position of the vector.
   v.insert(v.begin() + 1, MemoryBlock(50));
}

该示例产生下面的输出:

In MemoryBlock(size_t). length = 25.
In MemoryBlock(MemoryBlock&&). length = 25. Moving resource.
In ~MemoryBlock(). length = 0.
In MemoryBlock(size_t). length = 75.
In MemoryBlock(MemoryBlock&&). length = 25. Moving resource.
In ~MemoryBlock(). length = 0.
In MemoryBlock(MemoryBlock&&). length = 75. Moving resource.
In ~MemoryBlock(). length = 0.
In MemoryBlock(size_t). length = 50.
In MemoryBlock(MemoryBlock&&). length = 50. Moving resource.
In MemoryBlock(MemoryBlock&&). length = 50. Moving resource.
In operator=(MemoryBlock&&). length = 75.
In operator=(MemoryBlock&&). length = 50.
In ~MemoryBlock(). length = 0.
In ~MemoryBlock(). length = 0.
In ~MemoryBlock(). length = 25. Deleting resource.
In ~MemoryBlock(). length = 50. Deleting resource.
In ~MemoryBlock(). length = 75. Deleting resource.

前Visual C++ 2010,本示例将生成以下输出:

In MemoryBlock(size_t). length = 25.
In MemoryBlock(const MemoryBlock&). length = 25. Copying resource.
In ~MemoryBlock(). length = 25. Deleting resource.
In MemoryBlock(size_t). length = 75.
In MemoryBlock(const MemoryBlock&). length = 25. Copying resource.
In ~MemoryBlock(). length = 25. Deleting resource.
In MemoryBlock(const MemoryBlock&). length = 75. Copying resource.
In ~MemoryBlock(). length = 75. Deleting resource.
In MemoryBlock(size_t). length = 50.
In MemoryBlock(const MemoryBlock&). length = 50. Copying resource.
In MemoryBlock(const MemoryBlock&). length = 50. Copying resource.
In operator=(const MemoryBlock&). length = 75. Copying resource.
In operator=(const MemoryBlock&). length = 50. Copying resource.
In ~MemoryBlock(). length = 50. Deleting resource.
In ~MemoryBlock(). length = 50. Deleting resource.
In ~MemoryBlock(). length = 25. Deleting resource.
In ~MemoryBlock(). length = 50. Deleting resource.
In ~MemoryBlock(). length = 75. Deleting resource.

此示例使用移动语义的版本不会执行更少的副本、 内存分配和解除分配内存的操作不使用移动语义的版本比效率更高。

可靠编程

若要防止资源泄露,始终在移动赋值运算符释放资源 (如内存、 文件句柄和套接字)。

若要防止出现不可恢复的资源进行破坏,正确处理 self-assignment 中移动赋值运算符。

如果为您的类提供一个移动的构造函数,并移动赋值运算符,您可以通过编写移动构造函数调用移动赋值运算符来消除冗余代码。 下面的示例显示了移动构造函数调用移动赋值运算符的修订的版本:

// Move constructor.
MemoryBlock(MemoryBlock&& other)
   : _data(NULL)
   , _length(0)
{
   *this = std::move(other);
}

Std::move 函数保留的 rvalue 属性other参数。

请参见

参考

Rvalue引用声明:&&

其他资源

<utility> move