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.)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this case, yes; but the reason is quite subtle.
The parentheses in
new bool()cause value-initialisation, which initialises it asfalse. Without them,new boolwill 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
newat 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.