I make the first enum a "safe" default value in my C++ code, but I cannot find an "official" guideline to quote to back up this practice.
Consider the struct:
struct MyNuke {
enum {
Detonate,
Disable
} state;
};
I'm using a C++03 compiler. I cannot add a constructor because the struct is used in a union. I cannot get rid of the union because that is not my code.
Calling the default constructor zero-initializes the struct members:
MyNuke nuke = MyNuke();
The value of nuke.state is now Detonate. Disable would be a safer first value.
It seems logical to make the first enum a "safe" value. Are there any C++ guidelines on this?
There are no guidelines for this, as guidelines are not targeted to legacy code. To the contrary, they are targeted to code which will be written in five years. And as they clearly discourage usage of unions, they will not have a suggestion on how to add safe first value to the union.
However, in C++03 the question is valid, and the answer is what you are doing yourself. Since X() does value-initialize object and it's members, which is 0-initialization for enums, your enum will be initialized to first element (since it has value of 0 by default). However, please note that X x; does not do this, so the safety is not that great.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With