Espacios de nombres
Variantes
Acciones

Move assignment operator

De cppreference.com
< cpp‎ | language

 
 
Lenguaje C++
Los temas generales
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.
Control de flujo
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.
Sentencias condicionales ejecución
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.
Instrucciones de iteración
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 declaraciones
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.
Funciones
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaración de la función
lambda declaración de la función
función de plantilla
especificador inline
especificaciones de excepción (obsoleto)
noexcept especificador (C++11)
Excepciones
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los espacios de nombres
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)
Los 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
almacenamiento duración especificadores
constexpr especificador (C++11)
auto especificador (C++11)
alignas especificador (C++11)
Inicialización
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los literales
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expresiones
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representaciones alternativas
Utilidades
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
alias de tipo de declaración (C++11)
atributos (C++11)
Lanza
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversiones implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-cast estilo y funcional
De asignación de memoria
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.
Clases
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Clase propiedades específicas de la función
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.
Funciones especiales miembro
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 asignación
mover asignación (C++11)
destructor
Plantillas
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
clase de plantilla
función de plantilla
plantilla de especialización
paquetes de parámetros (C++11)
Varios
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Montaje en línea
 
Un operador de asignación movimiento 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&&, const T&&, volatile T&& o const volatile T&&. Un tipo con un operador de movimiento asignación pública es 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.

Contenido

[editar] Sintaxis

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

# Declaración típica de un operador de asignación movimiento
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.
# Obligar a un operador de asignación movimiento que se genere por el 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.
# Evitar la asignación movimiento 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.
El operador de asignación movimiento se llama cada vez que se selecciona por sobrecarga resolución, por ejemplo, cuando un objeto aparece en el lado izquierdo de una expresión de asignación, donde el lado derecho es un valor p del mismo tipo o convertible implícitamente .
Original:
The move assignment operator is called whenever it is selected by sobrecarga resolución, 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.
Mueva los operadores de asignación típicamente "robar" los recursos mantenidos por el argumento (por ejemplo, punteros a objetos dinámicamente asignados, los descriptores de archivos, sockets TCP, I / O, hilos corrientes de funcionamiento, etc), en lugar de hacer copias de ellos, y dejar el argumento en un estado válido, pero indeterminado de otra manera. Por ejemplo, el movimiento de la asignación de un std::string o de un std::vector deja el argumento mano derecha vacía .
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.

[editar] Implícitamente, declarado operador mover asignación

Si no definidos por el usuario operadores de asignación se mueven se proporcionan para un tipo de clase (struct, class o union), y todas las siguientes condiciones:
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.
  • no hay constructores de copia declaradas por el usuario
    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.
  • No hay constructores movimiento declarados por el usuario
    Original:
    there are no user-declared move constructors
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • no hay operadores de copia por el usuario declara asignación
    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.
  • No hay destructores declarados por el usuario
    Original:
    there are no user-declared destructors
    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 movimiento implícitamente declarada no sería definido como eliminado
    Original:
    the implicitly-declared move assignment operator 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.
entonces el compilador declarar un operador de asignación se mueven como miembro inline public de su clase con el firma
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.
Una clase puede tener varios operadores de asignación se mueven, por ejemplo, tanto T& T::operator=(const T&&) y T& T::operator=(T&&). Si algunos definidos por el usuario de operadores de asignación movimiento están presentes, el usuario todavía puede forzar la generación de la asignación implícita movimiento operador declarado con la palabra clave 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.
Debido a que algunas operador de asignación (mover o copiar) 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 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.

[editar] Suprimido implícitamente declarada operador mover asignación

El operador de asignación movimiento 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 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.
  • 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 de datos que no se pueden mover-asignado (se ha borrado, inaccesible, o ambiguo movimiento operador de asignación)
    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 tiene clase base directa o virtual que no se puede mover-asignado (se ha borrado, inaccesible, o ambiguo movimiento operador de asignación)
    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 tiene un miembro no estático de datos o una base directa o virtual sin necesidad de un operador de asignación movimiento que no es trivial copiable .
    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 tiene una clase virtual de base directa o indirecta
    Original:
    T has a direct or indirect virtual base class
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Movimiento Trivial operador de asignación

El operador de asignación movimiento implícitamente declarado para T clase es trivial si todo lo siguiente es cierto:
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.
  • 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 movimiento seleccionado para cada base directa de T es trivial
    Original:
    The move 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 movimiento seleccionado para cada tipo de clase no estática (o matriz de tipo de clase) memeber de T es trivial
    Original:
    The move 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 movimiento trivial realiza la misma acción que el assignmentoperator copia trivial, es decir, 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 mover asignable .
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.

[editar] Implícitamente operador definido movimiento asignación

Si el operador de movimiento asignación implícita-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, el operador de asignación movimiento 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 de asignación movimiento realiza miembro de pleno derecho-sabio asignación movimiento de bases del objeto y de los miembros no estáticos, en su orden de inicialización, utilizando una función de asignación para los escalares y operador de asignación movimiento para los tipos de clase .
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.

[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.
La copia-y-swap operador de asignación
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.

T& T::operator=(T arg) {
    swap(arg);
    return *this;
}

realiza una asignación equivalente de movimiento para los argumentos rvalue al costo de una llamada adicional al constructor movimiento de T, que a menudo es aceptable .
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.

[editar] Ejemplo

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

Output:

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