◐ Shell
clean mode source ↗

Move constructors - cppreference.com

De cppreference.com

<metanoindex/>

Um construtor movimento de T classe é um construtor não-modelo, cujo primeiro parâmetro é T&&, const T&&, volatile T&&, const volatile T&& ou e ou não existem outros parâmetros, ou o resto dos parâmetros têm valores padrão. Um tipo com um construtor movimento público é MoveConstructible.

Original:

A move constructor of class T is a non-template constructor whose first parameter is T&&, const T&&, volatile T&&, or const volatile T&&, and either there are no other parameters, or the rest of the parameters all have default values. A type with a public move constructor is MoveConstructible.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Sintaxe

class_name ( class_name && ) (1) (desde C++11)
class_name ( class_name && ) = default; (2) (desde C++11)
class_name ( class_name && ) = delete; (3) (desde C++11)

Explicação

# Declaração típica de um construtor de movimento

Original:

# Typical declaration of a move constructor

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

# Forçando um construtor movimento a ser gerado pelo compilador

Original:

# Forcing a move constructor to be generated by the compiler

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

# Evitar construtor movimento implícito

Original:

# Avoiding implicit move constructor

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

O construtor movimento é chamado sempre que um objeto é inicializado de xValue do mesmo tipo, o que inclui

Original:

The move constructor is called whenever an object is initialized from xvalue of the same type, which includes

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

  • inicialização, ou T a = std::move(b); T a(std::move(b));, onde b é de T tipo

    Original:

    initialization, T a = std::move(b); or T a(std::move(b));, where b is of type T

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • passagem de argumentos de função: f(std::move(a));, onde a é do tipo T e f é void f(T t)

    Original:

    function argument passing: f(std::move(a));, where a is of type T and f is void f(T t)

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • retorno da função: return a; dentro de uma função, como T f(), onde a é de T tipo que tem um construtor movimento.

    Original:

    function return: return a; inside a function such as T f(), where a is of type T which has a move constructor.

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Mova construtores normalmente "roubar" os recursos mantidos pelo argumento (por exemplo, os ponteiros para objetos dinamicamente alocados, descritores de arquivos, sockets TCP, I / O córregos, threads em execução, etc), em vez de fazer cópias delas e deixe o argumento em algum estado válido, mas de outra forma indeterminada. Por exemplo, movendo-se a partir de uma ou de um std::string std::vector transforma o argumento vazio.

Original:

Move constructors typically "steal" the resources held by the argument (e.g. pointers to dynamically-allocated objects, file descriptors, TCP sockets, I/O streams, running threads, etc), rather than make copies of them, and leave the argument in some valid but otherwise indeterminate state. For example, moving from a std::string or from a std::vector turns the argument empty.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Implicitamente declarou construtor movimento

Se nenhum construtor definidas pelo usuário mover são fornecidas para um tipo de classe (struct, class, ou union), e todo o seguinte é verdadeiro:

Original:

If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true:

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

  • não há construtores usuário-declarados cópia

    Original:

    there are no user-declared copy constructors

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • não há operadores de atribuição usuário declarado de cópia

    Original:

    there are no user-declared copy assignment operators

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • não há operadores de atribuição usuário declarou movimento

    Original:

    there are no user-declared move assignment operators

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • não há destructurs usuário-declarados

    Original:

    there are no user-declared destructurs

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • o construtor movimento implicitamente declarado não pode ser definido como excluído

    Original:

    the implicitly-declared move constructor would not be defined as deleted

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

em seguida, o compilador irá declarar um construtor movimento como um membro inline public de sua classe com o T::T(T&&) assinatura

Original:

then the compiler will declare a move constructor as an inline public member of its class with the signature T::T(T&&)

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Uma classe pode ter construtores mover várias, como por exemplo tanto T::T(const T&&) e T::T(T&&). Se alguns construtores definidos pelo usuário mover estão presentes, o usuário pode ainda forçar a geração do construtor movimento implicitamente declarado com a palavra-chave default.

Original:

A class can have multiple move constructors, e.g. both T::T(const T&&) and T::T(T&&). If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword default.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Excluídos implicitamente declarou construtor movimento

O construtor movimento implicitamente declarado ou inadimplente para T classe é definida como excluídos em qualquer uma das seguintes situações:

Original:

The implicitly-declared or defaulted move constructor for class T is defined as deleted in any of the following is true:

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

  • T tem membros não-estáticos de dados que não podem ser movidos (ter apagado, inacessível, ou construtores movimento ambíguos)

    Original:

    T has non-static data members that cannot be moved (have deleted, inaccessible, or ambiguous move constructors)

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T tem classe base direta ou virtual que não pode ser movido (apagou, inacessível, ou construtores movimento ambíguos)

    Original:

    T has direct or virtual base class that cannot be moved (has deleted, inaccessible, or ambiguous move constructors)

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T tem classe base direta ou virtual com um destruidor excluído ou inacessível

    Original:

    T has direct or virtual base class with a deleted or inaccessible destructor

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T tem um definido pelo usuário construtor movimento ou operador de atribuição movimento

    Original:

    T has a user-defined move constructor or move assignment operator

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T é uma união e tem um membro variante com não-trivial construtor de cópia

    Original:

    T is a union and has a variant member with non-trivial copy constructor

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T tem um não-membro estático de dados ou uma base direta ou virtual sem um construtor movimento que não é trivial copiável.

    Original:

    T has a non-static data member or a direct or virtual base without a move constructor that is not trivially copyable.

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Construtor movimento trivial

O construtor movimento implicitamente declarado para T classe é trivial se todo o seguinte é verdadeiro:

Original:

The implicitly-declared move constructor for class T is trivial if all of the following is true:

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

  • T não tem funções de membro virtual

    Original:

    T has no virtual member functions

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • T não tem classes base virtuais

    Original:

    T has no virtual base classes

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • O construtor movimento selecionado para cada base direta de T é trivial

    Original:

    The move constructor selected for every direct base of T is trivial

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

  • O construtor movimento selecionado para cada tipo de classe não-estático (ou matriz do tipo classe) memeber de T é trivial

    Original:

    The move constructor selected for every non-static class type (or array of class type) memeber of T is trivial

    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

Um construtor movimento trivial é um construtor que realiza a mesma ação que o construtor de cópia trivial, isto é, faz uma cópia da representação do objeto como se por std::memmove. Todos os tipos de dados compatíveis com a linguagem C (tipos POD) são trivialmente móvel.

Original:

A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially movable.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Implicitamente definido construtor movimento

Se o construtor movimento implicitamente declarado não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador. Para os tipos de union, o construtor movimento implicitamente definido copia a representação do objeto (como por std::memmove). Para os tipos não-sindicalizados classe (class e struct), o construtor movimento realiza jogada membro-sábio cheio de bases do objeto e membros não-estáticos, em sua ordem de inicialização, usando a inicialização direto com um argumento xValue.

Original:

If the implicitly-declared move constructor is not deleted or trivial, it is defined (that is, a function body is generated and compiled) by the compiler. For union types, the implicitly-defined move constructor copies the object representation (as by std::memmove). For non-union class types (class and struct), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Notas

Para fazer garantia exceção forte possível, construtores definidos pelo usuário movimento não deve lançar exceções. Na verdade, contêineres padrão normalmente contam com std::move_if_noexcept de escolher entre mover e copiar quando elementos de contêineres precisarão ser realocadas.

Original:

To make strong exception guarantee possible, user-defined move constructors should not throw exceptions. In fact, standard containers typically rely on std::move_if_noexcept to choose between move and copy when container elements need to be relocated.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Se a cópia e construtores movimento são fornecidos, a resolução de sobrecarga seleciona o construtor movimento se o argumento é uma' rvalue (ou' prvalue como um temporário sem nome ou' xValue como o resultado de std::move) e seleciona o construtor de cópia, se o argumento é' lvalue (objeto nomeado ou uma função / operador de voltar lvalue referência). Se apenas o construtor de cópia é fornecida, todas as categorias de argumento selecioná-lo (desde que leva referência a const, desde rvalues ​​pode ligar para referências const), que faz a cópia do recurso para mover-se, quando se deslocam está indisponível.

Original:

If both copy and move constructors are provided, overload resolution selects the move constructor if the argument is an rvalue (either prvalue such as a nameless temporary or xvalue such as the result of std::move), and selects the copy constructor if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy constructor is provided, all argument categories select it (as long as it takes reference to const, since rvalues can bind to const references), which makes copying the fallback for moving, when moving is unavailable.

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Em muitas situações, os construtores se movem são otimizados, mesmo se eles produziriam observáveis ​​efeitos colaterais, consulte elisão cópia

Original:

In many situations, move constructors are optimized out even if they would produce observable side-effects, see elisão cópia

The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Exemplo

#include <string>
#include <iostream>

struct A {
    std::string s;
    A() : s("test") {}
    A(const A& o) : s(o.s) { std::cout << "move failed!\n";}
    A(A&& o) : s(std::move(o.s)) {}
};

A f(A a) {
    return a;
}

struct B : A {
     std::string s2; 
     int n;
     // implicit move-contructor B::(B&&)
     // calls A's move constructor
     // calls s2's move constructor
     // and makes a bitwise copy of n
};

struct C : B {
    ~C() {}; // destructor prevents implicit move
};

struct D : B {
    D() {}
    ~D() {}; // destructor would prevent implicit move
    D(D&&) = default; // force a move ctor anyway
};

int main()
{
    std::cout << "Trying to move A\n";
    A a1 = f(A()); // move-construct from rvalue temporary
    A a2 = std::move(a1); // move-construct from xvalue

    std::cout << "Trying to move B\n";
    B b1;
    std::cout << "Before move, b1.s = \"" << b1.s << "\"\n";
    B b2 = std::move(b1); // calls implicit move ctor
    std::cout << "After move, b1.s = \"" << b1.s << "\"\n";

    std::cout << "Trying to move C\n";
    C c1;
    C c2 = std::move(c1); // calls the copy constructor

    std::cout << "Trying to move D\n";
    D d1;
    D d2 = std::move(d1);
}

Saída:

Trying to move A
Trying to move B
Before move, b1.s = "test"
After move, b1.s = ""
Trying to move C
move failed!
Trying to move D