Is there a C ++ directive to make the first enum "safe" by default?
I make the first enum a "safe" default in my C ++ code, but I can't find an "official" guide to quote to support this practice.
Consider the structure:
struct MyNuke {
enum {
Detonate,
Disable
} state;
};
I am using the C ++ 03 compiler. I cannot add a constructor because the struct is being used in union. I cannot get rid of the union because it is not my code.
Calling the null null constructor - initializes the structure members:
MyNuke nuke = MyNuke();
The nuke.state value is now Detonate
. Disable
would be the safer first value.
It seems logical to make the first enum a "safe" value. Are there any guidelines in C ++?
source to share
There is no recommendation for this, as the recommendation does not target legacy code. Instead, they target code that will be written five years from now. And since they are clearly discouraging the use of unions, they will have no suggestion on how to add a safe first meaning to the union.
However, in C ++ 03 the question is valid, and the answer is what you do yourself. Since it X()
initializes value-initialize and its members, which is null initialization for enums, your enum will be initialized with the first element (since it defaults to 0). However, note that X x;
it doesn't, so the security isn't all that great.
source to share
From > C ++ Coding Standard :
Make a shortcut to uninitialized or erroneous state. Do it first if possible.
source to share