Copy constructors
Da 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. |
Um construtor de cópia da classe
T
é um construtor não-modelo, cujo primeiro parâmetro é T&, const T&, volatile T&, const volatile T& ou e ou não existem outros parâmetros, ou o resto dos parâmetros têm valores padrão. Um tipo com um construtor de cópia público é CopyConstructible
.Original:
A copy 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 copy constructor is CopyConstructible
.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.
Índice |
[editar] Sintaxe
class_name ( const class_name & )
|
(1) | ||||||||
class_name ( const class_name & ) = default;
|
(1) | ||||||||
class_name ( const class_name & ) = delete;
|
(1) | ||||||||
[editar] Explicação
# Declaração típica de um construtor de cópia
Original:
# Typical declaration of a copy 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.
# Forçando um construtor de cópia a ser gerado pelo compilador
Original:
# Forcing a copy 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 construtor padrão implícito
Original:
# Avoiding implicit default 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.
O construtor de cópia é chamado sempre que um objeto é inicializado a partir de um outro objeto do mesmo tipo, o que inclui
Original:
The copy constructor is called whenever an object is initialized from another object 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.
- inicialização, ou T a = b; T a(b);, onde b é de
T
tipoOriginal:initialization, T a = b; or T a(b);, where b is of typeT
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - passagem de argumentos de função: f(a);, onde
a
é do tipoT
ef
é void f(T t)Original:function argument passing: f(a);, wherea
is of typeT
andf
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 da função: return a; dentro de uma função, como T f(), onde
a
é deT
tipo, que não tem nenhum construtor movimento.Original:function return: return a; inside a function such as T f(), wherea
is of typeT
, which has no move constructor.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 construtor de cópia
Se não definidos pelo usuário construtores de cópia são fornecidas para um tipo de classe (struct, class, union ou), o compilador sempre declarar um construtor de cópia como membro
inline public
de sua classe. Este construtor de cópia implicitamente declarado tem o T::T(const T&)
forma se todo o seguinte é verdadeiro:Original:
If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as an
inline public
member of its class. This implicitly-declared copy constructor has the form T::T(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.
You can help to correct and verify the translation. Click here for instructions.
- todas as bases diretos e virtual de
T
tem construtores de cópia com referências a const ou a const volátil como seus primeiros parâmetrosOriginal:all direct and virtual bases ofT
have copy constructors with references to const or to const volatile as their first parametersThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - todos os membros não-estáticos de
T
tem construtores de cópia com referências a const ou a const volátil como seus primeiros parâmetrosOriginal:all non-static members ofT
have copy constructors with references to const or to const volatile as their first parametersThe 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 construtor de cópia implicitamente declarado é T::T(T&). (Note-se que devido a estas regras, o construtor de cópia implicitamente declarou não pode se ligar a um argumento lvalue volátil)
Original:
Otherwise, the implicitly-declared copy constructor is T::T(T&). (Note that due to these rules, the implicitly-declared copy constructor 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.
You can help to correct and verify the translation. Click here for instructions.
Uma classe pode ter construtores de cópias múltiplas, por exemplo, tanto T::T(const T&) e T::T(T&). Se alguns construtores definidos pelo usuário cópia estão presentes, o usuário pode ainda forçar a geração do construtor de cópia implicitamente declarado com a palavra-chave
default
(desde C++11).Original:
A class can have multiple copy constructors, e.g. both T::T(const T&) and T::T(T&). If some user-defined copy constructors are present, the user may still force the generation of the implicitly declared copy constructor with the keyword
default
(desde C++11).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] Excluídos implicitamente declarou construtor de cópia
O construtor de cópia implicitamente declarado ou inadimplente para
T
classe é (até C++11) indefinido / definido como excluídos (desde C++11) em qualquer uma das seguintes situações:Original:
The implicitly-declared or defaulted copy constructor for class
T
is undefined (até C++11) / defined as deleted (desde C++11) 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.
-
T
tem membros não-estáticos de dados que não podem ser copiados (ter apagado, inacessível, ou construtores de cópia ambíguos)Original:T
has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors)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 copiado (apagou, construtores de cópia de difícil acesso, ou ambígua)Original:T
has direct or virtual base class that cannot be copied (has deleted, inaccessible, or ambiguous copy constructors)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 com um destruidor excluído ou inacessívelOriginal:T
has 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. -
T
tem um definido pelo usuário construtor movimento ou movimento (desde C++11) operador de atribuiçãoOriginal:T
has a user-defined move constructor or move assignment operator (desde C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. -
T
é uma união e tem um membro variante com não-trivial (desde C++11) construtor de cópiaOriginal:T
is a union and has a variant member with non-trivial copy constructor (desde C++11)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 de dados de rvalue (desde C++11) tipo de referênciaOriginal:T
has a data member of rvalue reference type (desde C++11)The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Construtor de cópia trivial
O construtor de cópia implicitamente declarado para
T
classe é trivial se todo o seguinte é verdadeiro:Original:
The implicitly-declared copy 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.
-
T
não tem funções de membro virtualOriginal:T
has 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. -
T
não tem classes base virtuaisOriginal:T
has 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. - O construtor de cópia selecionado para cada base direta de
T
é trivialOriginal:The copy constructor selected for every direct base ofT
is trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions. - O construtor de cópia selecionado para cada tipo de classe não-estático (ou matriz do tipo classe) memeber de
T
é trivialOriginal:The copy constructor selected for every non-static class type (or array of class type) memeber ofT
is trivialThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Um construtor de cópia trivial é um construtor que cria uma cópia bytewise da representação objeto do argumento, e não executa nenhuma outra ação. Objetos com construtores de cópia triviais podem ser copiados, copiando suas representações de objetos manualmente, por exemplo, com std::memmove. Todos os tipos de dados compatíveis com a linguagem C (tipos POD) são trivialmente copiável.
Original:
A trivial copy constructor is a constructor that creates a bytewise copy of the object representation of the argument, and performs no other action. Objects with trivial copy constructors can be copied by copying their object representations manually, e.g. with std::memmove. All data types compatible with the C language (POD types) are trivially copyable.
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] Implicitamente definido construtor de cópia
Se o construtor de cópia implicitamente declarado não é excluído ou trivial, é definido (isto é, um corpo de função é gerado e compilado) pelo compilador. Para os tipos de union, o construtor 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 construtor executa cópia membro-sábio cheio de bases do objeto e membros não-estáticos, em sua ordem de inicialização, usando a inicialização direta.
Original:
If the implicitly-declared copy 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 copy constructor copies the object representation (as by std::memmove). For non-union class types (class and struct), the constructor performs full member-wise copy of the object's bases and non-static members, in their initialization order, using direct initialization.
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.
A geração do construtor de cópia implicitamente definido é deprecated(desde C++11) se
T
tem um definido pelo usuário destruidor ou operador definido pelo usuário atribuição de cópia.Original:
The generation of the implicitly-defined copy constructor is deprecated(desde C++11) if
T
has a user-defined destructor or user-defined 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.
You can help to correct and verify the translation. Click here for instructions.
[editar] Notas
Em muitas situações, construtores de cópia são otimizados, mesmo se eles produziriam observáveis efeitos colaterais, consulte elisão cópia
Original:
In many situations, copy constructors are optimized out even if they would produce observable side-effects, see elisão cópia
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] Exemplo
struct A { int n; A(int n=1) : n(n) {} A(const A& a) : n(a.n) {} // user-defined copy ctor }; struct B : A { // implicit default ctor B::B() // implicit copy ctor B::B(const B&) }; struct C : B { C() : B() {} private: C(const C&); // non-copiable, C++98 style }; int main() { A a1(7); A a2(a1); // calls the copy ctor B b; B b2 = b; A a3 = b; // conversion to A& and copy ctor volatile A va(10); // A a4 = va; // compile error C c; // C c2 = c; // compile error }