Espacios de nombres
Variantes
Acciones

Move constructors

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.
default constructor
copiar constructor
mover constructor (C++11)
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 constructor movimiento de T clase es un constructor no-plantilla cuyo primer parámetro es T&&, const T&&, volatile T&& o const volatile T&&, y, o bien no existen otros parámetros, o el resto de los parámetros tienen valores por defecto. Un tipo con un constructor movimiento pública es 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.

Contenido

[editar] Sintaxis

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)

[editar] Explicación

# Declaración típica de un constructor movimiento
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.
# Obligar a un constructor paso a ser generado por el 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 el constructor movimiento 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.
El constructor de movimiento se llama siempre que un objeto es inicializado desde xValue del mismo tipo, que incluye
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.
  • inicialización, T a = std::move(b); o T a(std::move(b));, donde b es de tipo T
    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.
  • que pasa función argumento: f(std::move(a));, donde a es de tipo T y f es 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 de la función: return a; dentro de una función, como T f(), donde a es de T tipo que tiene un constructor movimiento .
    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.
Mueva constructores típicamente "robar" los recursos mantenidos por el argumento (por ejemplo, punteros a objetos dinámicamente asignados, los descriptores de archivos, sockets TCP, E / S arroyos, hilos de ejecución, etc), en lugar de hacer copias de ellos, y dejar el argumento en un estado válido, pero indeterminado de otra manera. Por ejemplo, pasar de un std::string o de un std::vector convierte el argumento vacío .
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.

[editar] Implícitamente, declarado constructor movimiento

Si no se mueven los constructores definidos por el usuario se preveía un tipo de clase (struct, class o union), y todas las siguientes condiciones:
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.
  • 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 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 operadores se mueven por el usuario declara asignación
    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.
  • no hay destructurs declarados por el usuario
    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.
  • el constructor movimiento implícitamente declarada no sería definido como eliminado
    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.
entonces el compilador declarar un constructor movimiento como miembro inline public de su clase con el T::T(T&&) firma
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.
Una clase puede tener varios constructores se mueven, por ejemplo, tanto T::T(const T&&) y T::T(T&&). Si algunos constructores de movimiento definidos por el usuario están presentes, el usuario todavía puede forzar la generación del constructor movimiento implícitamente declarado con la palabra clave 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.

[editar] Suprimido implícitamente declarada constructor movimiento

El constructor se mueven 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 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 tiene miembros no estáticos de datos que no se pueden mover (se han borrado, inaccesible, o constructores ambiguas Mover)
    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 tiene clase base directa o virtual que no se pueden mover (se ha borrado, inaccesible, o constructores ambiguas Mover)
    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 tiene clase base directa o virtual con un destructor borrado o inaccesible
    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 tiene un constructor definido por el usuario o el operador de asignación movimiento mudanza
    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 es un sindicato y tiene un miembro variante con constructor de copia no trivial
    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 tiene un miembro no estático de datos o una base directa o virtual sin un constructor movimiento que no es trivial copiable .
    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.

[editar] Constructor movimiento Trivial

El constructor se mueven implícitamente declarado para T clase es trivial si todo lo siguiente es cierto:
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 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 constructor de movimiento seleccionado para cada base directa de T es 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.
  • El constructor de movimiento seleccionado para cada tipo de clase no estática (o matriz de tipo de clase) memeber de T es 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.
Un constructor movimiento trivial es un constructor que realiza la misma acción que el constructor de 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 móvil .
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.

[editar] Implícitamente definido constructor movimiento

Si el constructor movimiento 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, el constructor 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 constructor movimiento realiza miembro de pleno derecho-acierto de las bases del objeto y de los miembros no estáticos, en su orden de inicialización, el uso directo de inicialización con un 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.

[editar] Notas

Para hacer posible una fuerte garantía de excepción definidos por el usuario constructores movimiento no debe lanzar excepciones. De hecho, los contenedores estándar normalmente se basan en std::move_if_noexcept que elegir entre mover y copiar cuando elementos contenedores deben ser reubicados .
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.
Si tanto copiar y mover constructores se proporcionan, la resolución de sobrecarga selecciona el constructor movimiento si el argumento es un valor p' ( bien prvalue como un temporal sin nombre o xValue como el resultado de std::move) y selecciona el constructor de copia si el argumento es lvalue' (objeto con nombre o una función / operador regresar lvalue referencia). Si sólo el constructor de copia se proporciona, de todas las categorías de argumento seleccionarlo (el tiempo que tarda referencia a const, ya que se puede unir a rvalues ​​referencias const), que hace que copiar el repliegue para mover, cuando se mueve no está disponible .
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.
En muchas situaciones, los constructores se mueven están optimizados, incluso si se produjera observables efectos secundarios, copia elisión ver
Original:
In many situations, move constructors are optimized out even if they would produce observable side-effects, see copia elisión
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>
 
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);
}

Output:

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