Espaços nominais
Variantes
Acções

copy initialization

Da cppreference.com
< cpp‎ | language

 
 
Linguagem C++
Tópicos gerais
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.
Controle de fluxo
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.
Declarações execução condicional
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.
Instruções de iteração
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 declarações
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.
Funções
Original:
Functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
declaração da função
lambda declaração da função
modelo de função
linha especificador
especificações de exceção(obsoleta)
noexcept especificador(C++11)
Exceções
Original:
Exceptions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Namespaces
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)
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
armazenamento duração especificadores
constexpr especificador(C++11)
auto especificador(C++11)
alignas especificador(C++11)
Inicialização
Original:
Initialization
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Literais
Original:
Literals
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Expressões
Original:
Expressions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
representações alternativas
Utilitários
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
tipo de alias declaração(C++11)
atributos(C++11)
Conversões
Original:
Casts
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
conversões implícitas
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
Elenco C-estilo e funcional
Alocação de memória
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.
Classes
Original:
Classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Classe propriedades específicas de função
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.
Funções membro especiais
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.
Modelos
Original:
Templates
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
modelo de classe
modelo de função
especialização de modelo
pacotes de parâmetros(C++11)
Diversos
Original:
Miscellaneous
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Assembly embutido
 
Inicializa um objeto de outro objeto
Original:
Initializes an object from another object
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

Índice

[editar]Sintaxe

Tobject= other; (1)
f(other); (2)
return other; (3)
catch (Tother) ; (4)
Tarray[N] = { other}; (5)

[editar]Explicação

Inicialização cópia será realizada nas seguintes situações:
Original:
Copy initialization is performed in the following situations:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
1)
quando uma variável chamada (automático, estático ou segmento local) é declarada com o inicializador constituído por um sinal de igual seguido por uma expressão.
Original:
when a named variable (automatic, static, or thread-local) is declared with the initializer consisting of an equals sign followed by an expression.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
2)
ao passar um argumento para uma função por valor
Original:
when passing an argument to a function by value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
3)
ao retornar de uma função que retorna por valor
Original:
when returning from a function that returns by value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
4)
quando captura uma exceção por valor
Original:
when catching an exception by value
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
5)
como parte de inicialização agregada, para inicializar cada elemento para o qual um inicializador é fornecido
Original:
as part of inicialização agregada, to initialize each element for which an initializer is provided
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Os efeitos de cópia de inicialização são:
Original:
The effects of copy initialization are:
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
  • Se T é um tipo de classe e do tipo de other é cv não qualificado versão do T ou uma classe derivada de T, os construtores de T são examinados ea melhor combinação é selecionada por resolução de sobrecarga. O construtor é então chamado para inicializar o objeto.
    Original:
    If T is a class type and the type of other is cv-unqualified version of T or a class derived from T, the constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Se T é um tipo de classe, e o tipo de other é diferente, ou se não é T classe tipo, mas o tipo de other é uma classe de tipo definido pelo usuário seqüências de conversão, que pode converter a partir do tipo de other para T são examinados e melhor um é selecionado através de resolução de sobrecarga. O resultado da conversão, que é um prvalue temporária do tipo de destino, é então utilizado para dirigir-inicializar o objeto. O último passo é geralmente eliminado eo resultado da função de conversão é construída diretamente na memória alocada para o objeto alvo, mas o construtor de cópia é exigida para ser acessível mesmo que ela não é usada.
    Original:
    If T is a class type, and the type of other is different, or if T is non-class type, but the type of other is a class type, definido pelo usuário seqüências de conversão that can convert from the type of other to T are examined and the best one is selected through overload resolution. The result of the conversion, which is a prvalue temporary of the destination type, is then used to dirigir-inicializar the object. The last step is usually eliminado and the result of the conversion function is constructed directly in the memory allocated for the target object, but the copy constructor is required to be accessible even though it's not used.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Caso contrário (se não T nem o tipo de other são tipos de classes), conversões standard são usados, se necessário, para converter o valor de other à versão não qualificado de cv-T.
    Original:
    Otherwise (if neither T nor the type of other are class types), conversões standard are used, if necessary, to convert the value of other to the cv-unqualified version of T.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar]Notas

Cópia de inicialização é menos permissiva do que dirigir-inicialização: cópia de inicialização somente considera não-explícitas construtores e funções definidas pelo usuário de conversão.
Original:
Copy-initialization is less permissive than direct-initialization: copy-initialization only considers non-explicit constructors and user-defined conversion functions.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Se other é uma expressão rvalue, mover construtor serão selecionados por resolução de sobrecarga e chamou durante a cópia de inicialização-.
Original:
If other is an rvalue expression, mover construtor will be selected by overload resolution and called during copy-initialization.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
O sinal de igual, =, em cópia de inicialização de uma variável chamada não está relacionado com o operador de atribuição. Sobrecargas operador de atribuição não têm efeito sobre cópia de inicialização-.
Original:
The equals sign, =, in copy-initialization of a named variable is not related to the assignment operator. Assignment operator overloads have no effect on copy-initialization.
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.

[editar]Exemplo

#include <string>#include <utility>#include <memory>   int main(){std::string s ="test";// OK: constructor is non-explicitstd::string s2 =std::move(s);// this copy-initialization performs a move   // std::unique_ptr<int> p = new int(1); // error: constructor is explicitstd::unique_ptr<int> p(new int(1));// OK: direct-initialization   int n =3.14;// floating-integral conversionconstint b = n;// const doesn't matterint c = b;// ...either way}


[editar]Veja também

close