Move constructors
De 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. |
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.
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.
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.
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.
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.
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
TOriginal: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
aes de tipoTyfes void f(T t)Original: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
aes deTtipo que tiene un constructor movimiento .Original:function return: return a; inside a function such as T f(), whereais of typeTwhich 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.
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.
You can help to correct and verify the translation. Click here for instructions.
- no hay constructores de copia declaradas por el usuarioOriginal: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. - no hay operadores de copia por el usuario declara asignaciónOriginal: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. - no hay operadores se mueven por el usuario declara asignaciónOriginal:there are no user-declared move assignment operatorsThe 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 usuarioOriginal:there are no user-declared destructursThe 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 eliminadoOriginal:the implicitly-declared move constructor 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.
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.
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.
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.
You can help to correct and verify the translation. Click here for instructions.
-
Ttiene miembros no estáticos de datos que no se pueden mover (se han borrado, inaccesible, o constructores ambiguas Mover)Original:Thas 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. -
Ttiene clase base directa o virtual que no se pueden mover (se ha borrado, inaccesible, o constructores ambiguas Mover)Original:Thas 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. -
Ttiene clase base directa o virtual con un destructor borrado o inaccesibleOriginal:Thas direct or virtual base class with a deleted or inaccessible destructorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Ttiene un constructor definido por el usuario o el operador de asignación movimiento mudanzaOriginal:Thas a user-defined move constructor or move assignment operatorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Tes un sindicato y tiene un miembro variante con constructor de copia no trivialOriginal:Tis a union and has a variant member with non-trivial copy constructorThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
Ttiene un miembro no estático de datos o una base directa o virtual sin un constructor movimiento que no es trivial copiable .Original:Thas 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.
You can help to correct and verify the translation. Click here for instructions.
-
Tno tiene funciones miembro virtualesOriginal:Thas 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. -
Tno tiene clases base virtualesOriginal:Thas 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. - El constructor de movimiento seleccionado para cada base directa de
Tes trivialOriginal:The move constructor selected for every direct base ofTis trivialThe 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
Tes trivialOriginal:The move constructor selected for every non-static class type (or array of class type) memeber ofTis trivialThe 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.
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.
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.
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.
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.
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