(C++) 初始化列表 std::initializer_list

构造时直接使用初始化列表

T object { arg1, arg2, ... };                  (1)
T { arg1, arg2, ... }                          (2)
new T { arg1, arg2, ... }                      (3)
Class { T member { arg1, arg2, ... }; };       (4)
Class::Class() : member{arg1, arg2, ...} {...  (5)

赋值使用初始化列表

T object = {arg1, arg2, ...};                  (6)
function( { arg1, arg2, ... } )                (7)
return { arg1, arg2, ... } ;                   (8)
object[ { arg1, arg2, ... } ]                  (9)
object = { arg1, arg2, ... }                   (10)
U( { arg1, arg2, ... } )                       (11)
Class { T member = { arg1, arg2, ... }; };     (12)

使用初始化列表初始化实例

struct S {
  std::string str1;
  int a1;
  std::string str2;
  std::string str3;
};

S s1 {"abc", 1, "bbb", "ccc"}; // ok, will init in order
S s2 {"abc", 1, {"bbb"}, "ccc"}; // ok

std::pair<std::string, int> p {"10086", 10010};
std::vector<std::pair<std::string, int>> v {
  {"10000", 200},
  {"10010", 300},
  {"10086", 400},
};

注意:这种{...}形式的初始化参数,是没有类型信息的,不能直接作为变量。

使用 std::initializer_list

An object of type std::initializer_list is a lightweight proxy object that provides access to an array of objects of type const T.

A std::initializer_list object is automatically constructed when:

  • a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an std::initializer_list parameter
  • a braced-init-list is used as the right operand of assignment or as a function call argument, and the corresponding assignment operator/function accepts an std::initializer_list parameter
  • a braced-init-list is bound to auto, including in a ranged for loop

Initializer lists may be implemented as a pair of pointers or pointer and length. Copying a std::initializer_list does not copy the underlying objects

参考

posted @ 2022-09-26 20:48  山岚2013  阅读(250)  评论(0编辑  收藏  举报