Move assignment operator
Da cppreference.com
![]() |
This page has been machine-translated from the English version of the wiki using Google Translate.
The translation may contain errors and awkward wording. Hover over text to see the original version. You can help to fix errors and improve the translation. For instructions click here. |
Um operador de atribuição movimento de
T
classe é um modelo não-função membro não-estático com a operator= nome que leva exatamente um parâmetro do tipo T&&, const T&&, volatile T&&, ou const volatile T&&. Um tipo com um operador público movimento atribuição é MoveAssignable
.Original:
A move assignment operator of class
T
is a non-template non-static member function with the name operator= that takes exactly one parameter of type T&&, const T&&, volatile T&&, or const volatile T&&. A type with a public move assignment operator is MoveAssignable
.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Índice |
[editar] Sintaxe
class_name & class_name :: operator= ( class_name && )
|
(1) | (desde C++11) | |||||||
class_name & class_name :: operator= ( class_name && ) = default;
|
(2) | (desde C++11) | |||||||
class_name & class_name :: operator= ( class_name && ) = delete;
|
(3) | (desde C++11) | |||||||
[editar] Explicação
# Declaração típica de um operador de atribuição movimento
Original:
# Typical declaration of a 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.
You can help to correct and verify the translation. Click here for instructions.
# Forçando um operador de atribuição movimento a ser gerado pelo compilador
Original:
# Forcing a move assignment operator 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.
You can help to correct and verify the translation. Click here for instructions.
# Evitar atribuição movimento implícito
Original:
# Avoiding implicit move assignment
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
O operador de atribuição movimento é chamado sempre que é selecionado por resolução de sobrecarga, por exemplo, quando um objecto aparece no lado esquerdo de uma expressão de atribuição, em que o lado direito é um rvalue do mesmo tipo ou implicitamente conversível.
Original:
The move assignment operator is called whenever it is selected by resolução de sobrecarga, e.g. when an object appears on the left side of an assignment expression, where the right-hand side is an rvalue of the same or implicitly convertible type.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Mova operadores de atribuição 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 deixar o argumento em algum estado válido, mas de outra forma indeterminada. Por exemplo, mover-atribuição de uma std::string ou de um std::vector deixa o argumento lado direito vazio.
Original:
Move assignment operators 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, move-assigning from a std::string or from a std::vector leaves the right-hand side argument empty.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Implicitamente declarou operador de atribuição movimento
Se não definidos pelo usuário operadores de atribuição movimento são fornecidas para um tipo de classe (struct, class, union ou), e todo o seguinte é verdadeiro:
Original:
If no user-defined move assignment operators 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.
You can help to correct and verify the translation. Click here for instructions.
- não há construtores usuário-declarados cópiaOriginal:there are no user-declared copy constructorsThe 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 movimentoOriginal:there are no user-declared move constructorsThe 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ópiaOriginal:there are no user-declared copy assignment operatorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - Não existem destrutores usuário-declaradosOriginal:there are no user-declared destructorsThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - o operador de atribuição implicitamente declarou movimento não pode ser definido como excluídoOriginal:the implicitly-declared move assignment operator would not be defined as deletedThe 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 operador de atribuição movimento como um membro
inline public
de sua classe com o
assinatura Original:
then the compiler will declare a move assignment operator as an
inline public
member of its class with the signature
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
Uma classe pode ter operadores mover várias atribuição, por exemplo, tanto T& T::operator=(const T&&) e T& T::operator=(T&&). Se alguns operadores definidos pelo usuário atribuição movimento estão presentes, o usuário pode ainda forçar a geração do operador implicitamente declarado movimento atribuição com a palavra-chave
default
.Original:
A class can have multiple move assignment operators, e.g. both T& T::operator=(const T&&) and T& T::operator=(T&&). If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator 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.
You can help to correct and verify the translation. Click here for instructions.
Porque alguns operador de atribuição (mover ou copiar) é sempre declarado para qualquer classe, a base de operador de atribuição de classe está sempre escondido. Se um utilizando-declaração é usado para trazer o operador de atribuição da classe base, e seu tipo de argumento poderia ser o mesmo que o tipo de argumento do operador de atribuição implícita da classe derivada, usando a declaração também é escondido pela implícito declaração.
Original:
Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Excluídos implicitamente declarou operador de atribuição movimento
O operador de atribuição implicitamente declarado ou inadimplente movimento para
T
classe é definida como excluídos em qualquer uma das seguintes situações:Original:
The implicitly-declared or defaulted move assignment operator 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.
You can help to correct and verify the translation. Click here for instructions.
-
T
tem um membro não-estático de dados que é constOriginal:T
has a non-static data member that is constThe 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 de um tipo de referência.Original:T
has a non-static data member of a reference type.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 que não podem mover-se atribuído (já excluído, inacessível, ou operador de atribuição ambígua movimento)Original:T
has a non-static data member that cannot be move-assigned (has deleted, inaccessible, or ambiguous 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
tem classe base direta ou virtual que não podem mover-se atribuído (já excluído, inacessível, ou operador de atribuição ambígua movimento)Original:T
has direct or virtual base class that cannot be move-assigned (has deleted, inaccessible, or ambiguous 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
tem um não-membro estático de dados ou uma base direta ou virtual sem um operador de atribuição movimento que não é trivial copiável.Original:T
has a non-static data member or a direct or virtual base without a move assignment operator 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. -
T
tem uma classe base direta ou indireta virtualOriginal:T
has a direct or indirect virtual base classThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Operador de atribuição trivial movimento
O operador de atribuição implicitamente declarou movimento para
T
classe é trivial se todo o seguinte é verdadeiro:Original:
The implicitly-declared move assignment operator 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.
You can help to correct and verify the translation. Click here for instructions.
-
T
não tem funções de membro virtualOriginal:T
has no virtual member functionsThe 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 virtuaisOriginal:T
has no virtual base classesThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - O operador de atribuição movimento selecionado para cada base direta de
T
é trivialOriginal:The move assignment operator selected for every direct base ofT
is trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - O operador de atribuição movimento selecionado para cada tipo de classe não-estático (ou matriz do tipo classe) memeber de
T
é trivialOriginal:The move assignment operator selected for every non-static class type (or array of class type) memeber ofT
is trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Um operador de atribuição trivial movimento realiza a mesma ação que o assignmentoperator 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 mover transmissível.
Original:
A trivial move assignment operator performs the same action as the trivial copy assignmentoperator, 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 move-assignable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Implicitamente definida operador de atribuição movimento
Se o operador de atribuição implicitamente declarou movimento não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador. Para os tipos de union, o operador de atribuição implicitamente definida movimento copia a representação do objeto (como por std::memmove). Para os tipos não-sindicalizados classe (class e struct), o operador de atribuição movimento realiza atribuição completa mudança membro sábio de bases do objeto e membros não-estáticos, em sua ordem de inicialização, usando built-in de atribuição para os escalares e operador de atribuição movimento para tipos de classe.
Original:
If the implicitly-declared move assignment operator 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 assignment operator copies the object representation (as by std::memmove). For non-union class types (class and struct), the move assignment operator performs full member-wise move assignment of the object's bases and non-static members, in their initialization order, using built-in assignment for the scalars and move assignment operator for class types.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Notas
Se a cópia e operadores de atribuição movimento são fornecidos, a resolução de sobrecarga seleciona a atribuição movimento se o argumento é uma' rvalue (ou' prvalue como um temporário sem nome ou' xValue como o resultado de std::move ), e seleciona a atribuição de cópia se o argumento é' lvalue (chamado objeto ou uma função / operador de voltar lvalue referência). Se apenas a cessão de cópia é fornecida, todas as categorias de argumento selecioná-lo (desde que leva o seu argumento por valor ou como referência para const, desde rvalues pode ligar para referências const), o que faz de atribuição de cópia do recurso para a atribuição de jogar, quando mover está indisponível.
Original:
If both copy and move assignment operators are provided, overload resolution selects the move assignment 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 assignment if the argument is lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
O operador de atribuição de copiar-e-swap
Original:
The copy-and-swap assignment operator
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
T& T::operator=(T arg) {
swap(arg);
return *this;
}
executa o equivalente a atribuição de movimento para argumentos rvalue ao custo de uma chamada adicional para o construtor movimento de T, que muitas vezes é aceitável.
Original:
performs an equivalent of move assignment for rvalue arguments at the cost of one additional call to the move constructor of T, which is often acceptable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
You can help to correct and verify the translation. Click here for instructions.
[editar] Exemplo
#include <string> #include <iostream> #include <utility> 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& operator=(const A&) { std::cout << "copy assigned\n"; return *this; } A& operator=(A&& other) { s = std::move(other.s); std::cout << "move assigned\n"; return *this; } }; A f(A a) { return a; } struct B : A { std::string s2; int n; // implicit move assignment operator B& B::operator=(B&&) // calls A's move assignment operator // calls s2's move assignment operator // and makes a bitwise copy of n }; struct C : B { ~C() {}; // destructor prevents implicit move assignment }; struct D : B { D() {} ~D() {}; // destructor would prevent implicit move assignment D& operator=(D&&) = default; // force a move assignment anyway }; int main() { A a1, a2; std::cout << "Trying to move-assign A from rvalue temporary\n"; a1 = f(A()); // move-assignment from rvalue temporary std::cout << "Trying to move-assign A from xvalue\n"; a2 = std::move(a1); // move-assignment from xvalue std::cout << "Trying to move-assign B\n"; B b1, b2; std::cout << "Before move, b1.s = \"" << b1.s << "\"\n"; b2 = std::move(b1); // calls implicit move assignment std::cout << "After move, b1.s = \"" << b1.s << "\"\n"; std::cout << "Trying to move-assign C\n"; C c1, c2; c2 = std::move(c1); // calls the copy assignment operator std::cout << "Trying to move-assign E\n"; D d1, d2; d2 = std::move(d1); }
Saída:
Trying to move-assign A from rvalue temporary move assigned Trying to move-assign A from xvalue move assigned Trying to move-assign B Before move, b1.s = "test" move assigned After move, b1.s = "" Trying to move-assign C copy assigned Trying to move-assign E move assigned