在结构中初始化默认值

如果我只需要初始化一个 C + + 结构的几个选择值,这样做是否正确:

struct foo {
foo() : a(true), b(true) {}
bool a;
bool b;
bool c;
} bar;

我是否可以假设我最终会得到一个名为 barstruct项目,其中包含 bar.a = truebar.b = true和一个未定义的 bar.c元素?

214108 次浏览

Yes. bar.a and bar.b are set to true, but bar.c is undefined. However, certain compilers will set it to false.

See a live example here: struct demo

According to C++ standard Section 8.5.12:

if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

For primitive built-in data types (bool, char, wchar_t, short, int, long, float, double, long double), only global variables (all static storage variables) get default value of zero if they are not explicitly initialized.

If you don't really want undefined bar.c to start with, you should also initialize it like you did for bar.a and bar.b.

You can do it by using a constructor, like this:

struct Date
{
int day;
int month;
int year;


Date()
{
day=0;
month=0;
year=0;
}
};

or like this:

struct Date
{
int day;
int month;
int year;


Date():day(0),
month(0),
year(0){}
};

In your case bar.c is undefined,and its value depends on the compiler (while a and b were set to true).

You don't even need to define a constructor

struct foo {
bool a = true;
bool b = true;
bool c;
} bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

An explicit default initialization can help:

struct foo {
bool a {};
bool b {};
bool c {};
} bar;

Behavior bool a {} is same as bool b = bool(); and return false.