次の方法で共有


方法: 移動コンストラクターを作成します

ここで記述する方法について説明、 のコンス トラクターを移動と C++ クラスの移動代入演算子。移動コンス トラクターを使用すると、移動の形式は、アプリケーションのパフォーマンスが大幅に向上させることができますを実装できます。移動のセマンティクスの詳細についてを参照してください右辺値参照宣言子: &&

次の 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. 次の例に示すように、そのパラメーターとして、クラス型への右辺値参照を取得する空のコンス トラクター メソッドを定義します。

    MemoryBlock(MemoryBlock&& other)
       : _data(NULL)
       , _length(0)
    {
    }
    
  2. 移動コンス トラクターでは、クラスのデータ メンバーは、ソース オブジェクトから生成されるオブジェクトに割り当てます。

    _data = other._data;
    _length = other._length;
    
  3. ソース オブジェクトのデータ メンバーにデフォルト値を割り当てます。これにより、デストラクター リソース (メモリ) などを複数回解放からを防ぐことができます。

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

C++ クラスの移動代入演算子を作成するのには

  1. 次の例に示すように、パラメーターとして、クラス型、右辺値への参照を受け取り、クラス型への参照を返しますが空の代入演算子を定義します。

    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;
}

次の使用例では移動のセマンティクスが、アプリケーションのパフォーマンスを向上させるためです。例では、ベクトル オブジェクトに 2 つの要素を追加し、2 つの既存の要素の間で新しい要素を挿入します。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 関数の右辺値プロパティを保持する、 otherパラメーター。

参照

関連項目

右辺値参照宣言子: &&

その他の技術情報

<utility> move