Espacios de nombres
Variantes
Acciones

list initialization

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.
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
 
Inicializa un objeto de braced-init-list
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.

Contenido

[editar] Sintaxis

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] Explicación

Lista de inicialización se lleva a cabo en las siguientes situaciones:
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.
1)
inicialización de una variable llamada con un aparato ortopédico-lista cerrada de expresiones o listas anidadas (preparé-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.
2)
inicialización de un temporal sin nombre con una lista preparó-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.
3)
inicialización de un objeto con el tiempo de almacenamiento dinámico con una nueva expresión, donde el inicializador es un aparato ortopédico-init-list
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.
4)
en un comunicado return con braced-init-list utiliza como expresión 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.
5)
en una expresión de llamada a la función, se preparó con-init-list utilizado como 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.
6)
en una expresión subíndice con un operador definido por el usuario []
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.
7)
en una expresión de conversión funcional o de otro tipo de inicialización directa, con preparé-init-list utiliza como argumento del constructor
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.
8)
en un inicializador de miembro no estático de datos
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.
9)
en una lista de inicialización del constructor
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.
10)
en el lado derecho del lado del signo igual (similar a copia de inicialización)
Original:
on the right-hand-side of the equals sign (similar to copia de inicialización)
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
Los efectos de la inicialización de un objeto lista de T tipo son:
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.
  • Si la lista braced-init-está vacía y T es un tipo de clase con un constructor por defecto, valor de inicialización se realiza .
    Original:
    If the braced-init-list is empty and T is a class type with a default constructor, valor de inicialización is performed.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • De lo contrario, si T es una especialización de std::initializer_list, un objeto std::initializer_list nuevo del mismo tipo que se construye y se utiliza para dirigir a inicializar o copiar inicializar el objeto de T tipo, dependiendo del contexto .
    Original:
    Otherwise, if T is a specialization of std::initializer_list, a new std::initializer_list object of the same type is constructed and used to direct-initialize or copy-initialize the object of type T, 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.
  • De lo contrario, los constuctors de T se consideran, en dos fases:
    Original:
    Otherwise, the constuctors of T 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 los constructores que toman std::initializer_list como único argumento, o como el primer argumento si el resto de argumentos tienen valores por defecto, se examinan, y acompañada de la resolución de sobrecarga contra un solo argumento de tipo std::initializer_list
    Original:
    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_list
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si la etapa anterior no produce una coincidencia, todos los constructores de T participar en la resolución de sobrecarga contra el conjunto de argumentos que consta de los elementos de la braced-init-list, con la restricción de que sólo las conversiones de restricción están permitidos. Si esta etapa produce un constructor explícito como la mejor opción para una copia de la lista de inicialización, la compilación falla (nota, en simple copia de inicialización, los constructores explícitos no se consideran en absoluto)
    Original:
    If the previous stage does not produce a match, all constructors of T 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.
  • De lo contrario, si es T tipo de referencia, un prvalue temporal del tipo de referencia es la lista inicializada, y la referencia está vinculada a la temporal .
    Original:
    Otherwise, if T 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.
  • De lo contrario, si la lista se preparó-init-tiene un solo elemento, es T directa inicializado o copia inicializada, dependiendo del contexto, excepto que las conversiones de restricción no se admiten .
    Original:
    Otherwise, if the braced-init-list has only one element, T is directa inicializado or copia inicializada, 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.
  • De lo contrario, si la lista se preparó-init-no tiene elementos, es 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] Reducir las conversiones

lista de inicialización de los límites permitidos por la conversiones implícitas prohíbe los siguientes:
Original:
list-initialization limits the allowed conversiones 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.
  • la conversión de un tipo de punto flotante a un tipo entero
    Original:
    conversion from a floating-point type to an integer type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • conversión de un long double a double o float y la conversión de double a float, excepto cuando la fuente es una expresión constante cuyo valor se puede almacenar exactamente en el tipo de destino
    Original:
    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 type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • conversión de un tipo de enumeración entero o sin ámbito de tipo entero que no puede representar todos los valores de la original, excepto donde origen es una expresión constante cuyo valor se puede almacenar exactamente en el tipo de destino
    Original:
    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 type
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.

[editar] Notas

Preparado-init-list no es una expresión y no tiene ningún tipo por su cuenta: por ejemplo, cuando se llama a una plantilla de función, se preparó-init-list argumento no puede ser utilizado para la deducción plantilla tipo. Una excepción especial se hace para el auto palabra clave, que deduce cualquier preparó-init-list 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.

[editar] Ejemplo

#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 << ' ';
}

Output:

world
0 1 1
abcd cd aa
1 a
2 abc
3 abcd
1 2 3 -1 -2 -3


[editar] Ver también