list initialization
Материал из 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. |
Инициализирует объект из фигурных-Init-списка
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.
Содержание |
[править] Синтаксис
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) | ||||||||
[править] Объяснение
Список инициализация выполняется в следующих ситуациях:
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)
инициализации переменной с именем фигурные скобки список выражений или вложенные списки (приготовился-INIT-лист)
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)
инициализации неназванный с временным приготовился-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)
инициализации объекта с динамическим срок хранения с новой выражения, где инициализатор фигурные инициализации списка
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)
В return заявление с вычисляемых-INIT-лист используется в качестве возвращаемого выражением
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)
В выражении вызова функции, с приготовился-INIT-лист используется в качестве аргумента
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)
В индексного выражения с определенной пользователем оператора []
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)
В функциональное выражение литые или других прямых инициализации, с приготовился-Init-лист используется в качестве аргумента конструктора
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)
в не-статический инициализатор элемента данных
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)
В списке инициализации конструктора
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)
на правой стороне от знака равенства (по аналогии с Копия инициализации)
Original:
on the right-hand-side of the equals sign (similar to Копия инициализации)
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 являются: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.
- Если фигурных-Init-список пуст и
Tэто класс с конструктором по умолчанию, Значение инициализации выполняется.Original:If the braced-init-list is empty andTis a class type with a default constructor, Значение инициализации is performed.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- В противном случае, если
Tпредставляет собой совокупность типов, совокупный инициализации выполняется.Original:Otherwise, ifTis an aggregate type, совокупный инициализации is performed.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- В противном случае, если
Tявляется специализацией std::initializer_list, новый объектstd::initializer_listтого же типа, построено и используется для направления инициализации или скопировать инициализировать объект типаT, в зависимости от контекста.Original:Otherwise, ifTis a specialization of std::initializer_list, a newstd::initializer_listobject 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.
- В противном случае, constuctors из
Tсчитается, в два этапа:Original:Otherwise, the constuctors ofTare 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.
- Все конструкторы, которые принимают std::initializer_list в качестве единственного аргумента, или в качестве первого аргумента, если остальные аргументы имеют значения по умолчанию, рассматриваются, и сопровождается перегрузкой резолюции против одного аргумента типа 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.
-
- Если на предыдущем этапе не производит матч, все конструкторы
Tучастие в разрешении перегрузки с набором аргументов, которые состоят из элементов из фигурных-Init-лист, с тем ограничением, что только сужающими не допускается. Если эта стадия создает явный конструктор, как наиболее подходящий для копирования списка инициализации, компиляция не удается (к сведению, в простое копирование инициализации, явные конструкторы вообще не рассматриваются)Original:If the previous stage does not produce a match, all constructors ofTparticipate 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.
-
- В противном случае, если
Tявляется ссылочным типом, prvalue временное из указанного типа является список инициализации, и ссылка на связанный с этим временное.Original:Otherwise, ifTis 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.
- В противном случае, если уперся-Init-список имеет только один элемент,
Tявляется прямой инициализации или Копия инициализации, в зависимости от контекста, за исключением того, что сужение преобразования не допускается.Original:Otherwise, if the braced-init-list has only one element,Tis прямой инициализации or Копия инициализации, 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.
- В противном случае, если уперся-Init-лист не содержит элементов,
Tявляется Значение инициализации.Original:Otherwise, if the braced-init-list has no elements,Tis Значение инициализации.The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Сужение преобразований
Список инициализации ограничивает разрешенные неявные преобразования, запрещая следующие:
Original:
list-initialization limits the allowed неявные преобразования 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.
- преобразование из типа с плавающей точкой в целое число типаOriginal: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.
- Переход от long double в double или float и преобразования из double в float, кроме случаев, когда источником является постоянное выражение, значение которого может быть сохранен именно в целевой тип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 typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
- преобразование из целых или незаданной типа перечисления в целый тип, который не может представлять все значения оригинального, кроме случаев, когда источником является постоянным выражением, значение которого может быть сохранен именно в целевой тип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 typeThe text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
[править] Notes
Скрепленные-Init-список не является выражением и не имеет типа по себе: например, при вызове функции шаблона, подтянул-Init-список аргументов не может быть использована для шаблона вычета типа. Специальное исключение сделано для ключевого слова auto, которая выводит любую приготовился-Init-список, как 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.
[править] Пример
#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 << ' '; }
Вывод:
world 0 1 1 abcd cd aa 1 a 2 abc 3 abcd 1 2 3 -1 -2 -3