简体   繁体   中英

Difference in default initialization of struct members

struct Date1 {
  int day{1};
  int month{1};
  int year{2000};
};
struct Date2 {
  int day  =1;
  int month =1;
  int year =2000;
};
struct Date3 {
  Date() : day(1), month(1), year(2000) {}
  int day;
  int month;
  int year;
};

Is there any difference in terms of efficiency between those three options of default initialization of the struct member?

Is there any difference in terms of efficiency between those three options of default initialization of the struct member?

No. In class member initializers are just syntactic sugar for a member initialization list so they all generate the same code.

The real benefit comes from when you have multiple constructors like

struct Date {
  int day{1};
  int month{1};
  int year{2000};
  Date(int year) : year(year) {}
  Date(int year, int month) : year(year), month(month) {}
  Date(int year, int month, int day) : year(year), month(month), day(day) {}
};

versus

struct Date {
  int day;
  int month;
  int year;
  Date(int year) : year(year), month(1), day(1) {}
  Date(int year, int month) : year(year), month(month), day(1) {}
  Date(int year, int month, int day) : year(year), month(month), day(day) {}
};

In the first case if I need to change the default day, I only need to change it in once. In the second code block I have to update it twice, so it's more work and with more work comes more chances for getting it wrong.

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