Espaços nominais
Variantes
Acções

Copy assignment operator

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C++
Tópicos gerais
Original:
General topics
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Controle de fluxo
Original:
Flow control
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Declarações execução condicional
Original:
Conditional execution statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Instruções de iteração
Original:
Iteration statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Ir declarações
Original:
Jump statements
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção (obsoleta)
noexcept especificador (C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
Original:
Namespaces
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
decltype specifier (C++11)
Especificadores
Original:
Specifiers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
cv especificadores
armazenamento duração especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
Original:
Utilities
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Tipos
Original:
Types
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
typedef declaration
tipo de alias declaração (C++11)
atributos (C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
Original:
Memory allocation
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
Original:
Class-specific function properties
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Funções membro especiais
Original:
Special member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
copiar atribuição
mover atribuição (C++11)
destruidor
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros (C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Um operador de atribuição de cópia 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, T&, const T&, volatile T&, ou const volatile T&. Um tipo com um operador público cópia atribuição é CopyAssignable.
Original:
A copy 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, T&, const T&, volatile T&, or const volatile T&. A type with a public copy assignment operator is CopyAssignable.
The text has been machine-translated via Google Translate.
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= ( const class_name & ) (2) (desde C++11)
class_name & class_name :: operator= ( const class_name & ) = default; (3) (desde C++11)
class_name & class_name :: operator= ( const class_name & ) = delete; (4) (desde C++11)

[editar] Explicação

# Declaração típica de um operador de atribuição de cópia quando copy-and-swap idiom pode ser usado
Original:
# Typical declaration of a copy assignment operator when copy-and-swap idiom can be used
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Declaração típica de um operador de atribuição de cópia ao idioma de copiar e permuta-não pode ser utilizado
Original:
# Typical declaration of a copy assignment operator when copy-and-swap idiom cannot be used
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
# Forçar um operador de atribuição de cópia a ser gerado pelo compilador
Original:
# Forcing a copy 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.
# Evitar atribuição de cópia implícita
Original:
# Avoiding implicit copy assignment
The 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 de cópia é chamado sempre selecionados por resolução de sobrecarga, por exemplo, quando um objecto aparece no lado esquerdo de uma expressão de atribuição.
Original:
The copy assignment operator is called whenever selected by resolução de sobrecarga, e.g. when an object appears on the left side of an assignment expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Implicitamente declarou operador de atribuição de cópia

Se não definidos pelo usuário operadores de atribuição cópia são fornecidas para um tipo de classe (struct, class, ou union), o compilador sempre declarar um como membro inline público da classe. Este operador de atribuição implicitamente declarou cópia tem a T& T::operator=(const T&) forma se todo o seguinte é verdadeiro:
Original:
If no user-defined copy assignment operators are provided for a class type (struct, class, or union), the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T& T::operator=(const T&) 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.
  • cada base direta B de T tem um operador de atribuição de cópia cujos parâmetros são B ou const B& ou const volatile B&
    Original:
    each direct base B of T has a copy assignment operator whose parameters are B or const B& or const volatile B&
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • cada membro não-estático dados M de T de tipo de classe ou série de tipo de classe tem um operador de atribuição de cópia cujos parâmetros são M ou const M& ou const volatile M&
    Original:
    each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M& or const volatile M&
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
Caso contrário, o operador de atribuição implicitamente declarou cópia é declarado como T& T::operator=(T&). (Note-se que devido a estas regras, o operador de atribuição implicitamente declarou cópia não pode vincular a um argumento lvalue volátil)
Original:
Otherwise the implicitly-declared copy assignment operator is declared as T& T::operator=(T&). (Note that due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument)
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 múltiplas cópias operadores de atribuição, por exemplo, tanto T& T::operator=(const T&) e T& T::operator=(T). Se alguns operadores definidos pelo usuário atribuição de cópia estão presentes, o usuário pode ainda forçar a geração do operador implicitamente declarado cópia atribuição com a palavra-chave default.
Original:
A class can have multiple copy assignment operators, e.g. both T& T::operator=(const T&) and T& T::operator=(T). If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy 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.
Porque o operador de atribuição de cópia é 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 the copy assignment operator 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.

[editar] Excluídos implicitamente declarou operador de atribuição de cópia

O operador de atribuição implicitamente declarado ou inadimplente cópia para T classe é definida como excluídos em qualquer uma das seguintes situações:
Original:
The implicitly-declared or defaulted copy 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.
  • T tem um membro não-estático de dados que é const
    Original:
    T has a non-static data member that is const
    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 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-estático membro de dados que não pode ser cópia atribuído (já excluído, operador de atribuição inacessível, ou ambígua cópia)
    Original:
    T has a non-static data member that cannot be copy-assigned (has deleted, inaccessible, or ambiguous copy 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 pode ser cópia 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 copy-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 usuário declarou construtor movimento
    Original:
    T has a user-declared move 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 usuário declarou operador de atribuição movimento
    Original:
    T has a user-declared 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.

[editar] Operador de atribuição Trivial cópia

O operador de atribuição implicitamente declarou cópia para T classe é trivial se todo o seguinte é verdadeiro:
Original:
The implicitly-declared copy 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.
  • 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 operador de atribuição de cópia selecionado para cada base direta de T é trivial
    Original:
    The copy assignment operator 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 operador de atribuição de cópia selecionado para cada tipo de classe não-estático (ou matriz do tipo classe) memeber de T é trivial
    Original:
    The copy assignment operator 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 operador de atribuição trivial cópia 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 cópia transferível.
Original:
A trivial copy assignment operator makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially copy-assignable.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Implicitamente operador definido atribuição de cópia

Se o operador de atribuição implicitamente declarou cópia não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador. Para os tipos de union, a atribuição de cópia implicitamente definido copia a representação do objeto (como por std::memmove). Para os tipos não-sindicalizados classe (class e struct), o operador executa membro-sábio atribuição de cópia das bases do objeto e membros não-estáticos, em sua ordem de inicialização, usando, se usa a atribuição para os escalares e operador de atribuição de cópia para tipos de classe.
Original:
If the implicitly-declared copy 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 copy assignment copies the object representation (as by std::memmove). For non-union class types (class and struct), the operator performs member-wise copy assignment of the object's bases and non-static members, in their initialization order, using, using built-in assignment for the scalars and copy 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.
A geração do operador implicitamente definido cópia atribuição é deprecated(desde C++11) se T tem um destrutor usuário declarado ou user-declarou construtor de cópia.
Original:
The generation of the implicitly-defined copy assignment operator is deprecated(desde C++11) if T has a user-declared destructor or user-declared copy constructor.
The text has been machine-translated via Google Translate.
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.

[editar] Copie e trocar

Operador de atribuição de cópia pode ser expresso em termos de construtor de cópia, destruidor, eo swap () função de membro, se for fornecido:
Original:
Copy assignment operator can be expressed in terms of copy constructor, destructor, and the swap() member function, if one is provided:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

T& T::operator=(T arg) { // copy/move constructor is called to construct arg
    swap(arg);    // resources exchanged between *this and arg
    return *this;
}  // destructor is called to release the resources formerly held by *this

Para os não-arremesso de swap (), esta forma fornece garantia exceção forte. Para argumentos rvalue, este formulário automaticamente chama o construtor movimento, e é muitas vezes referida como "operador de atribuição unificadora" (como, cópia e movimento).
Original:
For non-throwing swap(), this form provides garantia exceção forte. For rvalue arguments, this form automatically invokes the move constructor, and is sometimes referred to as "unifying assignment operator" (as in, both copy and move).
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar] Exemplo

#include <iostream>
#include <memory>
struct A {
    int n;
    std::string s1;
    // user-defined copy assignment, copy-and-swap form
    A& operator=(A other) {
        std::cout << "copy assignment of A\n";
        std::swap(n, other.n);
        std::swap(s1, other.s1);
        return *this;
    }
};
 
struct B : A {
    std::string s2;
    // implicitly-defined copy assignment
};
 
struct C {
     std::unique_ptr<int[]> data;
     std::size_t size;
     // non-copy-and-swap assignment
     C& operator=(const C& other) {
         // check for self-assignment
         if(&other == this)
             return *this;
         // reuse storage when possible
         if(size != other.size)
             data.reset(new int[other.size]);
         std::copy(&other.data[0],
                   &other.data[0] + std::min(size, other.size),
                   &data[0]);
         return *this;
     }
     // note: copy-and-swap would always cause a reallocation
};
 
int main()
{
    A a1, a2;
    std::cout << "a1 = a2 calls ";
    a1 = a2; // user-defined copy assignment
 
    B b1, b2;
    b2.s1 = "foo";
    b2.s2 = "bar";
    std::cout << "b1 = b2 calls ";
    b1 = b2; // implicitly-defined copy assignment
    std::cout << "b1.s1 = " << b1.s1 << " b1.s2 = " << b1.s2 <<  '\n';
}

Saída:

a1 = a2 calls copy assignment of A
b1 = b2 calls copy assignment of A
b1.s1 = foo b1.s2 = bar