In C++, can I depend upon a new bool being initialized to false in all cases?
bool *myBool = new bool();
assert(false == *myBool); // Always the case in a proper C++ implementation?
(Updated code to reflect comment.)
In this case, yes; but the reason is quite subtle.
The parentheses in new bool()
cause value-initialisation, which initialises it as false
. Without them, new bool
will instead do default-initialisation, which leaves it with an unspecified value.
Personally, I'd rather see new bool(false)
if possible, to make it clear that it should be initialised.
(That's assuming that there is a good reason for using new
at all; and even if there is, it should be managed by a smart pointer - but that's beyond the scope of this question).
NOTE: this answers the question as it was when I read it; it had been edited to change its meaning after the other answer was written.