list initialization
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. |
Inicializa um objeto de braced-init-lista
Original:
Initializes an object from braced-init-list
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
T object { arg1, arg2, ... };
|
(1) | ||||||||
T { arg1, arg2, ... };
|
(2) | ||||||||
new T { arg1, arg2, ... };
|
(3) | ||||||||
return { arg1, arg2, ... } ;
|
(4) | ||||||||
function( { arg1, arg2, ... } ) ;
|
(5) | ||||||||
object[ { arg1, arg2, ... } ] ;
|
(6) | ||||||||
T( { arg1, arg2, ... } )
|
(7) | ||||||||
Class { T member = { arg1, arg2, ... }; };
|
(8) | ||||||||
Class:: Class() : member{ arg1, arg2, ...} {...
|
(9) | ||||||||
T object = { arg1, arg2, ...};
|
(10) | ||||||||
[editar] Explicação
Lista de inicialização é realizada nas seguintes situações:
Original:
List 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.
You can help to correct and verify the translation. Click here for instructions.
1)
inicialização de uma variável chamada com uma lista cinta-fechado de expressões ou listas aninhadas (preparou-init-list)
Original:
initialization of a named variable with a brace-enclosed list of expressions or nested lists (braced-init-list)
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.
2)
inicialização de um temporário sem nome com uma lista apoiou-init
Original:
initialization of an unnamed temporary with a braced-init-list
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.
3)
inicialização de um objeto com duração de armazenamento dinâmico, com uma expressão nova, onde o inicializador é uma cinta-init-lista
Original:
initialization of an object with dynamic storage duration with a new-expression, where the initializer is a brace-init-list
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.
4)
em comunicado return com braced-init-lista usada como a expressão de retorno
Original:
in a return statement with braced-init-list used as the return expression
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.
5)
em uma expressão chamada de função, com preparei-init-list usado como um argumento
Original:
in a function call expression, with braced-init-list used as an 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.
6)
em uma expressão subscrito com um operador definido pelo usuário []
Original:
in a subscript expression with a user-defined 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.
7)
em uma expressão de conversão funcional ou outro inicialização-direta, com preparei-init-lista usado como o argumento do construtor
Original:
in a functional cast expression or other direct-initialization, with braced-init-list used as the constructor 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.
8)
em um inicializador de membro não-estático de dados
Original:
in a non-static data member initializer
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.
9)
em uma lista de inicializador construtor
Original:
in a constructor initializer list
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.
10)
no lado direito do sinal de igual (semelhante ao cópia de inicialização)
Original:
on the right-hand-side of the equals sign (similar to cópia de inicialização)
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.
Os efeitos da inicialização lista de um objeto de
T
tipo são:Original:
The effects of list initialization of an object of type
T
are: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.
- Se a lista braced-init-se vazio e
T
é um tipo de classe com um construtor padrão, valor de inicialização é realizada.Original:If the braced-init-list is empty andT
is a class type with a default constructor, valor de inicialização is performed.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
T
é um tipo de agregado, inicialização agregada é realizado.Original:Otherwise, ifT
is an aggregate type, inicialização agregada is performed.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
T
é uma especialização de std::initializer_list, um objetostd::initializer_list
novo do mesmo tipo é construído e usado para dirigir-inicializar ou copiar-inicializar o objeto deT
tipo, dependendo do contexto.Original:Otherwise, ifT
is a specialization of std::initializer_list, a newstd::initializer_list
object of the same type is constructed and used to direct-initialize or copy-initialize the object of typeT
, depending on context.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, os constuctors de
T
são considerados, em duas fases:Original:Otherwise, the constuctors ofT
are considered, in two phases:The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- Todos os construtores que levam std::initializer_list como o único argumento, ou como o primeiro argumento, se os argumentos restantes têm valores padrão, são examinados, e acompanhado por resolução de sobrecarga contra um único argumento do tipo std::initializer_listOriginal:All constructors that take std::initializer_list as the only argument, or as the first argument if the remaining arguments have default values, are examined, and matched by overload resolution against a single argument of type std::initializer_listThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
-
- Se a etapa anterior não produz uma partida, todos os construtores de
T
participar de resolução de sobrecarga em relação ao conjunto de argumentos que consiste nos elementos da braced-lista-init, com a restrição de que apenas conversões de estreitamento são permitidos. Se nesta fase produz um construtor explícito como o melhor para uma cópia de lista de inicialização, compilação falhar (nota, em simples cópia de inicialização, construtores explícitos não são consideradas em todos)Original:If the previous stage does not produce a match, all constructors ofT
participate in overload resolution against the set of arguments that consists of the elements of the braced-init-list, with the restriction that only narrowing conversions are allowed. If this stage produces an explicit constructor as the best match for a copy-list-initialization, compilation fails (note, in simple copy-initialization, explicit constructors are not considered at all)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
T
é tipo de referência, um prvalue temporária do tipo referenciado é a lista inicializada, ea referência é vinculado a essa temporário.Original:Otherwise, ifT
is reference type, a prvalue temporary of the referenced type is list-initialized, and the reference is bound to that temporary.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 a lista preparou-init-tem apenas um elemento,
T
é direct-inicializado ou cópia inicializado, dependendo do contexto, exceto que as conversões de estreitamento não são permitidos.Original:Otherwise, if the braced-init-list has only one element,T
is direct-inicializado or cópia inicializado, depending on context, except that narrowing conversions are not allowed.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 a lista preparou-init-não tem elementos,
T
é valor inicializado.Original:Otherwise, if the braced-init-list has no elements,T
is valor inicializado.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Estreitando conversões
lista de inicialização-limita o conversões implícitas permitido ao proibir o seguinte:
Original:
list-initialization limits the allowed conversões implícitas by prohibiting the following:
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.
- conversão de um tipo de ponto flutuante para um tipo inteiroOriginal:conversion from a floating-point type to an integer typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- conversão de um long double para double ou float e conversão de double para float, salvo se a fonte é uma expressão constante cujo valor pode ser armazenado exatamente no tipo de destinoOriginal:conversion from a long double to double or to float and conversion from double to float, except where the source is a constant expression whose value can be stored exactly in the target typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- conversão do tipo de enumeração inteiro ou sem escopo de tipo inteiro que não pode representar todos os valores do original, salvo fonte é uma expressão constante cujo valor pode ser armazenado exatamente no tipo de destinoOriginal:conversion from integer or unscoped enumeration type to integer type that cannot represent all values of the original, except where source is a constant expression whose value can be stored exactly in the target typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[editar] Notas
Preparou-init-lista não é uma expressão e não tem nenhum tipo em seu próprio: por exemplo, ao chamar um modelo de função, preparou-init-lista argumento não pode ser utilizado para dedução do tipo de modelo. A exceção especial é feita para o auto palavra-chave, o que deduz qualquer preparou-init-lista como std::initializer_list.
Original:
Braced-init-list is not an expression and has no type on its own: for example, when calling a function template, braced-init-list argument cannot be used for template type deduction. A special exception is made for the keyword auto, which deduces any braced-init-list as std::initializer_list.
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
#include <iostream> #include <vector> #include <map> #include <string> struct Foo { std::vector<int> mem = {1,2,3}; // list-initialization of a non-static member std::vector<int> mem2; Foo() : mem2{-1, -2, -3} {} // list-initialization of a member in constructor }; std::pair<std::string, std::string> f(std::pair<std::string, std::string> p) { return {p.second, p.first}; // list-initialization in return statement } int main() { int n0{}; // value-initialization (to zero) int n1{1}; // direct-list-initialization std::string s1{'a', 'b', 'c', 'd'}; // initializer-list constructor call std::string s2{s1, 2, 2}; // regular constructor call std::string s3{0x61, 'a'}; // initializer-list ctor is preferred to (int, char) int n2 = {1}; // copy-list-initialization double d = double{1.2}; // list-initialization of a temporary, then copy-init std::map<int, std::string> m = { // nested list-initialization {1, "a"}, {2, {'a', 'b', 'c'} }, {3, s1} }; std::cout << f({"hello", "world"}).first // list-initialization in function call << '\n'; const int (&ar)[2] = {1,2}; // binds a lvalue reference to a temporary array int&& r1 = {1}; // binds a rvalue reference to a temporary int // int& r2 = {2}; // error: cannot bind rvalue to a non-const lvalue ref // int bad{1.0}; // error: narrowing conversion unsigned char uc1{10}; // okay // unsigned char uc2{-1}; // error: narrowing conversion Foo f; std::cout << n0 << ' ' << n1 << ' ' << n2 << '\n' << s1 << ' ' << s2 << ' ' << s3 << '\n'; for(auto p: m) std::cout << p.first << ' ' << p.second << '\n'; for(auto n: f.mem) std::cout << n << ' '; for(auto n: f.mem2) std::cout << n << ' '; }
Saída:
world 0 1 1 abcd cd aa 1 a 2 abc 3 abcd 1 2 3 -1 -2 -3