Jak: Konstruktor Przenieś zapisu
W tym temacie opisano, jak napisać przenieść konstruktora i operator przypisania Przenieś klasy C++.Konstruktor Przenieś umożliwiają implementowanie semantykę ruch, który może znacznie zwiększyć wydajność aplikacji.Aby uzyskać więcej informacji na temat Przenoszenie semantykę zobacz Odwołanie Rvalue; niewłaściwy deklarator: & &.
W tym temacie opiera się na następujące klasy C++, MemoryBlock, który zarządza buforu 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 != 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.
};
Poniższe procedury opisują jak napisać konstruktora przenoszenia i Przenieś operatorem przypisania, na przykład klasa C++.
Aby utworzyć Konstruktor Przenieś klasy C++
Należy zdefiniować metodę pustego konstruktora, który przyjmuje odwołanie rvalue typu klasy jako jej parametr, jak pokazano w następującym przykładzie:
MemoryBlock(MemoryBlock&& other) : _data(NULL) , _length(0) { }
W konstruktorze Przenieś do obiektu, który jest generowana należy przypisać członkowie klasy danych z obiektu źródłowego:
_data = other._data; _length = other._length;
Członkowie danych obiektu źródłowego można przypisać do wartości domyślnych.Zapobiega to destruktor zwalnianie zasobów (takich jak pamięć) wiele razy:
other._data = NULL; other._length = 0;
Aby utworzyć operatorem przypisania Przenieś klasy C++
Operator przypisania puste, odwołanie rvalue typu klasy jako parametr i zwraca odwołanie do typu klasy należy określić, jak pokazano w następującym przykładzie:
MemoryBlock& operator=(MemoryBlock&& other) { }
W Przenieś operatorem przypisania należy dodać instrukcję warunkową, która wykonuje żadnej operacji próby przypisać obiekt do samej siebie.
if (this != &other) { }
W instrukcji warunkowej pozbawione wszelkich zasobów (takich jak pamięć) jest przypisany do obiektu.
Poniższy przykład zwalnia _data Członkowskich z obiektu, który jest przypisywany do:
// Free the existing resource. delete[] _data;
Wykonaj kroki 2 i 3 w pierwszej procedury do przenoszenia elementów członkowskich danych z obiektu źródłowego do obiektu, który jest generowana:
// 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;
Zwraca odwołanie do bieżącego obiektu, jak pokazano w następującym przykładzie:
return *this;
Przykład
Poniższy przykład przedstawia kompletnego Konstruktor przenieść a operatorem przypisania dla MemoryBlock klasy:
// 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;
}
Poniższy przykład pokazuje, jak semantyka Przenieś może zwiększyć wydajność aplikacji.Przykład dodaje dwa elementy do obiektów wektorowych i wstawia nowy element między dwa istniejące elementy.W Visual C++ 2010, vector zastosowań klasy Przenieś semantykę do wykonania operacji wstawiania wydajnie, przenosząc elementy vector zamiast 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 = 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.
Przed Visual C++ 2010, ten przykład generuje następujące wyniki:
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, że zastosowań przenieść semantykę jest bardziej efektywne niż wersja używa semantykę przenoszenia, ponieważ wykonuje mniejszą liczbę kopii, alokacji pamięci i pamięci dezalokacji operacji.
Stabilne programowanie
Aby zapobiec przecieków zasobów, zawsze wolne zasobów (takich jak pamięć, dojścia do plików i gniazda) w Przenieś operatorem przypisania.
Aby zapobiec nieodwracalne zniszczenie zasobów, prawidłową obsługę self-assignment w Przenieś operatorem przypisania.
Jeżeli zarówno konstruktora przenoszenia i operator przypisania Przenieś klasy, można wyeliminować nadmiarowy kod pisząc konstruktora Przenieś wywołać operatora Przenieś przypisania.Poprawiona wersja konstruktora ruch, który wywołuje Przenieś operatorem przypisania można znaleźć w poniższym przykładzie:
// Move constructor.
MemoryBlock(MemoryBlock&& other)
: _data(NULL)
, _length(0)
{
*this = std::move(other);
}
Std::move funkcji zachowuje właściwości rvalue other parametru.
Zobacz też
Informacje
Odwołanie Rvalue; niewłaściwy deklarator: & &
Inne zasoby
<utility> move