c++ - struct 成员默认初始化的区别

标签 c++ c++11 struct

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

struct 成员的默认初始化这三个选项在效率方面有什么区别吗?

最佳答案

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



不。在类中,成员初始化器只是成员初始化列表的语法糖,因此它们都生成相同的代码。

当你有多个构造函数时,真正的好处来自于
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) {}
};

相对
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) {}
};

在第一种情况下,如果我需要更改默认日期,我只需要更改一次。在第二个代码块中,我必须更新它两次,所以工作量更大,而且工作量越多,出错的机会就越多。

关于c++ - struct 成员默认初始化的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61594521/

相关文章:

c++ - 为什么常量指针不能是常量表达式?

c - 在 .m 文件中访问作为全局变量的结构

c - 打印指向结构体的指针的二维数组

c++ - 当我在调用project()之前设置(CMAKE_EXECUTABLE_SUFFIX)时,CMake中的Emscripten不会输出html文件。为什么?我该如何修复它?

c++ - 如何将重载的成员函数作为参数传递?

C++ 实现抽象类

c++ - std::map::emplace() 缺失 - 过时的库?

c - 结构体,并将变量定义为同义词

c++ - 如何在 boost spirit 业力中将属性传递给子规则

c++ - 如何在程序和库之间传递一个值(使用 mkfifo 等)?