Espacios de nombres
Variantes
Acciones

Copy assignment operator

De cppreference.com
< cpp‎ | language
 
 
Lenguaje C++
Temas generales
Control de flujo
Instrucciones de ejecución condicionales
Instrucciones de iteración (bucles)
Declaraciones de salto
Funciones
Declaración de funciones
Declaración de funciones lambda
Especificador inline
Especificación de excepciones (hasta C++20)
Especificador noexcept (C++11)
Excepciones
Espacios de nombres
Tipos
Especificadores
decltype (C++11)
auto (C++11)
alignas (C++11)
Especificadores de duración de almacenamiento
Inicialización
Expresiones
Representaciones alternas
Literales
Booleanos - Enteros - De punto flotante
De carácter - De cadena - nullptr (C++11)
Definidos por el usuario (C++11)
Utilidades
Atributos (C++11)
Tipos
Declaración de typedef
Declaración de alias de tipo (C++11)
Conversiones
Conversiones implícitas - Conversiones explícitas
static_cast - dynamic_cast
const_cast - reinterpret_cast
Asignación de memoria
Clases
Propiedades de funciones específicas de la clase
Funciones miembro especiales
Operador de asignación de copia
Operador de asignación de movimiento (C++11)
Destructor
Plantillas
Misceláneos
 
Un operador de asignación de copia de T clase es un no-no estático plantilla función miembro con el operator= nombre que lleva exactamente un parámetro de tipo T, T&, const T&, volatile T& o const volatile T&. Un tipo con un operador de asignación de copia pública es 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.

Contenido

[editar] Sintaxis

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] Explicación

Declaración # típico de un operador de asignación de copia cuando copy-and-swap idiom se puede utilizar
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.
# Declaración típica de un operador de asignación de copia cuando modismo copy-and-swap no se puede utilizar
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.
# Obligar a un operador de asignación de copia que se generen por el 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 la asignación de copia implícito
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.
El operador de asignación de copia se llama cada vez seleccionado por sobrecarga resolución, por ejemplo, cuando un objeto aparece en el lado izquierdo de una expresión de asignación .
Original:
The copy assignment operator is called whenever selected by sobrecarga resolución, 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] Implícitamente, declarado operador de asignación de copia

Si no definidos por el usuario operadores de asignación de copia se preveía un tipo de clase (struct, class o union), el compilador siempre declarar una calidad de miembro en línea pública de la clase. Este operador de asignación de copia implícitamente declarada tiene la forma T& T::operator=(const T&) si todo lo siguiente es cierto:
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 directa B de T tiene un operador de asignación de copia, cuyos parámetros son B o const B& o 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 miembro no estático datos M de T de tipo de clase o matriz de tipo de clase tiene un operador de asignación de copia, cuyos parámetros son M o const M& o 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.
De lo contrario el operador de asignación de copia implícitamente declarada se declara como T& T::operator=(T&). (Tenga en cuenta que debido a estas reglas, el operador de asignación de copia implícitamente declarada no puede obligar a un volátil argumento valor-I)
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.
Una clase puede tener varios operadores de asignación de copia, por ejemplo, tanto T& T::operator=(const T&) y T& T::operator=(T). Si algunos definidos por el usuario de operadores de asignación de copia están presentes, el usuario todavía puede forzar la generación del operador de asignación de copia implícitamente declarado con la palabra clave 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.
Debido a que el operador de asignación de copia siempre se declara de cualquier clase, la clase base operador de asignación es siempre oculto. Si se utiliza-declaración se utiliza para traer el operador de asignación de la clase base, y su tipo de argumento podría ser el mismo que el tipo de argumento del operador de asignación implícita de la clase derivada, el uso de declaración también se oculta por el implícito declaración .
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] Suprimido implícitamente declarada operador de asignación de copia

El operador de asignación de copia implícitamente declaradas o cesación de pagos por T clase se define como borrado en cualquiera de las siguientes situaciones:
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 tiene un miembro no estático de datos que es 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 tiene un miembro no estático de datos de un tipo de referencia .
    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 tiene un miembro no estático datos que no pueden ser copia-asignado (se ha suprimido, operador de asignación de copia inaccesible, o ambiguo)
    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 tiene clase base directa o virtual que no puede ser copiado asignado (se ha borrado, inaccesible, o ambiguo movimiento operador de asignación)
    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 tiene el usuario declara constructor movimiento
    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 tiene un usuario declarado operador de asignación movimiento
    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] Copia Trivial operador de asignación

El operador de asignación de copia implícitamente declarado para T clase es trivial si todo lo siguiente es cierto:
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 no tiene funciones miembro virtuales
    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 no tiene clases base virtuales
    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.
  • El operador de asignación de copia seleccionado para cada base directa de T es 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.
  • El operador de asignación de copia seleccionado para cada tipo de clase no estática (o matriz de tipo de clase) memeber de T es 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.
Un operador de asignación de copia trivial hace una copia de la representación de objetos como por std::memmove. Todos los tipos de datos compatibles con el lenguaje C (tipos POD) son trivialmente copia asignable .
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] Implícitamente definida por el operador de asignación de copia

Si el operador de asignación de copia implícitamente-declarado no se elimina o trivial, se define (es decir, un cuerpo de función se genera y compila) por el compilador. Para los tipos de union, la asignación de copia implícitamente definido por copia la representación de objetos (como por std::memmove). Para los tipos de clase no sindicalizados (class y struct), el operador realiza miembros sabio asignación de copia de las bases del objeto y de los miembros no estáticos, en su orden de inicialización, usar, utilizando una función de asignación para los escalares y el operador de asignación de copia de tipos de clases .
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.
La generación del operador de asignación de copia implícitamente definido es si deprecated(desde C++11) T tiene un destructor usuario declaradas o declaradas por el usuario constructor copia .
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

Si tanto la copia y operadores de asignación se proporcionan movimiento, la resolución de sobrecarga selecciona la asignación de movimiento si el argumento es un valor R' (ya sea' prvalue tal como un temporal sin nombre o' xValue tal como el resultado de std::move ), y selecciona la asignación de copia si el argumento es' lvalue (llamado objeto o una función / operador regresar lvalue referencia). Si sólo la asignación de copia se proporciona, de todas las categorías de argumento seleccionarlo (el tiempo que toma su argumento por valor o como referencia a const, ya que se puede unir a rvalues ​​referencias const), lo que hace que la asignación de copia de reserva para la asignación de movimiento, cuando se mueven no está disponible .
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] Copia y cambiar

Operador de asignación de copia se puede expresar en términos de constructor de copia, destructor, y el intercambio () función miembro, si se proporciona:
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 los que no lanza swap (), esta forma proporciona garantía excepción fuerte. Para argumentos rvalue, esta forma automáticamente invoca el constructor movimiento, y se refiere a veces como "operador de asignación unificador" (como adentro, tanto copiar y mover) .
Original:
For non-throwing swap(), this form provides garantía excepción fuerte. 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] Ejemplo

#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';
}

Salida:

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