Konstruktory przenoszące i przenoszące operatory przypisania (C++)

W tym temacie opisano sposób pisania konstruktora przenoszenia i operatora przypisania przenoszenia dla klasy C++. Konstruktor przenoszenia umożliwia przenoszenie zasobów należących do obiektu rvalue do wartości lvalue bez kopiowania. Aby uzyskać więcej informacji na temat semantyki przenoszenia, zobacz Rvalue Reference Deklarator: &&.

W tym temacie przedstawiono następującą klasę języka C++, MemoryBlockktóra zarządza buforem pamięci.

// 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 != nullptr)
      {
         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.
};

Poniższe procedury opisują sposób pisania konstruktora przenoszenia i operatora przypisania przenoszenia dla przykładowej klasy C++.

Aby utworzyć konstruktor przenoszenia dla klasy C++

  1. Zdefiniuj pustą metodę konstruktora, która przyjmuje odwołanie rvalue do typu klasy jako parametru, jak pokazano w poniższym przykładzie:

    MemoryBlock(MemoryBlock&& other)
       : _data(nullptr)
       , _length(0)
    {
    }
    
  2. W konstruktorze przenoszenia przypisz składowe danych klasy z obiektu źródłowego do obiektu, który jest konstruowany:

    _data = other._data;
    _length = other._length;
    
  3. Przypisz elementy członkowskie danych obiektu źródłowego do wartości domyślnych. Zapobiega to wielokrotnemu zwalnianiu zasobów (takich jak pamięć) przez destruktor:

    other._data = nullptr;
    other._length = 0;
    

Aby utworzyć operator przypisania przenoszenia dla klasy C++

  1. Zdefiniuj pusty operator przypisania, który przyjmuje odwołanie rvalue do typu klasy jako parametr i zwraca odwołanie do typu klasy, jak pokazano w poniższym przykładzie:

    MemoryBlock& operator=(MemoryBlock&& other)
    {
    }
    
  2. W operatorze przypisania przenoszenia dodaj instrukcję warunkową, która nie wykonuje żadnej operacji, jeśli spróbujesz przypisać obiekt do samego siebie.

    if (this != &other)
    {
    }
    
  3. W instrukcji warunkowej zwolnij wszystkie zasoby (takie jak pamięć) z obiektu, do którego jest przypisywany.

    Poniższy przykład zwalnia _data element członkowski z obiektu, który jest przypisany do:

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

    Wykonaj kroki 2 i 3 w pierwszej procedurze, aby przenieść składowe danych z obiektu źródłowego do tworzonego obiektu:

    // 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;
    
  4. Zwróć odwołanie do bieżącego obiektu, jak pokazano w poniższym przykładzie:

    return *this;
    

Przykład: Ukończ konstruktor przenoszenia i operator przypisania

W poniższym przykładzie przedstawiono kompletny konstruktor przenoszenia i operator przypisania przenoszenia dla MemoryBlock klasy:

// Move constructor.
MemoryBlock(MemoryBlock&& other) noexcept
   : _data(nullptr)
   , _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 = nullptr;
   other._length = 0;
}

// Move assignment operator.
MemoryBlock& operator=(MemoryBlock&& other) noexcept
{
   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;
}

Przykład użycia semantyki przenoszenia w celu zwiększenia wydajności

W poniższym przykładzie pokazano, jak semantyka przenoszenia może poprawić wydajność aplikacji. W przykładzie dodano dwa elementy do obiektu wektorowego, a następnie wstawia nowy element między dwoma istniejącymi elementami. Klasa vector używa semantyki przenoszenia do wydajnego wykonywania operacji wstawiania przez przeniesienie elementów wektora zamiast ich kopiowania.

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

Ten przykład generuje następujące wyniki:

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 = 75. Moving resource.
In MemoryBlock(MemoryBlock&&). length = 25. Moving resource.
In ~MemoryBlock(). length = 0.
In ~MemoryBlock(). length = 0.
In MemoryBlock(size_t). length = 50.
In MemoryBlock(MemoryBlock&&). length = 50. Moving resource.
In MemoryBlock(MemoryBlock&&). length = 25. Moving resource.
In MemoryBlock(MemoryBlock&&). length = 75. Moving resource.
In ~MemoryBlock(). length = 0.
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.

Przed programem Visual Studio 2010 ten przykład wygenerował następujące dane wyjściowe:

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.

Wersja tego przykładu korzystająca z semantyki przenoszenia jest wydajniejsza niż wersja, która nie używa semantyki przenoszenia, ponieważ wykonuje mniej operacji kopiowania, alokacji pamięci i przydziału pamięci.

Niezawodne programowanie

Aby zapobiec wyciekom zasobów, zawsze wolne zasoby (takie jak pamięć, dojścia plików i gniazda) w operatorze przypisania przenoszenia.

Aby zapobiec nieodwracalnemu niszczeniu zasobów, należy prawidłowo obsługiwać samoprzypisania w operatorze przypisania przenoszenia.

Jeśli podasz zarówno konstruktor przenoszenia, jak i operator przypisania przenoszenia dla klasy, możesz wyeliminować nadmiarowy kod, pisząc konstruktor przenoszenia w celu wywołania operatora przypisania przenoszenia. W poniższym przykładzie pokazano poprawioną wersję konstruktora przenoszenia, który wywołuje operator przypisania przenoszenia:

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

Funkcja std::move konwertuje wartość lvalue other na wartość rvalue.

Zobacz też

Deklarator odwołania do wartości R: &&
std::move