다음을 통해 공유


방법: 이동 생성자 작성

이 항목을 작성 하는 방법을 설명는 생성자 이동 및 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