简体   繁体   中英

C++ initialization list and constructor

C++14 provides the initialization list and we can use it to initialize elements in a class or struct. What are the differences of the two initialization manners in the following code?

struct MyItem {
  MyItem() : val{0} {}
  int val;
};

struct MyItem {
  MyItem() {}
  int val{0};
};

In your case, there is no difference. The first case uses a mem-initializer to initialize val . The second uses a brace-or-equal-initializer . A brace-or-equal-initializer will be used for a member when there is no mem-initializer present for that member. If there is a mem-initializer , it takes precedence, and the brace-or-equal-initializer is ignored.

One can certainly construct contrived examples where there is a difference...

const int i = 42;

struct S1 {
    S1(int i): val{i} {} // sets val to the parameter i
    int val;
};

struct S2 {
    S2(int i) {} // param is ignored
    int val{i}; // sets val to 42
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM