Can I depend upon a new bool being initialized to false?

10,783

Solution 1

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.

Solution 2

The three relevant kinds of initialization, zero-initialization, default-initialization, and value-initialization for bool mean, respectively, that the bool is initialized to false, that the bool has an indeterminate value, and that the bool is initialized to false.

So you simply need to ensure that you're getting zero or value initialization. If an object with automatic or dynamic storage duration is initialized without an initializer specified then you get default-initialization. To get value-initialization you need an empty initializer, either () or {}.

bool b{}; // b is value-initialized
bool *b2 = new bool{}; // *b2 is value-initialized

class foo {
    bool b;
    foo() : b() {}
};
foo f; // // f.b is value-initialized

You get zero initialization for a bool that has static or thread local storage duration and does not have an initializer.

static bool b; // b is zero-initialized
thread_local bool b2; // b2 is zero-initialized

One other case where you get zero-initialization is if the bool is a member of a class without a user-provided constructor and the implicit default constructor is trivial, and the class instance is zero- or value-initialized.

class foo {
    bool b;
};
foo f{}; // f.b is zero-initialized
thread_local foo f2; // f2.b is zero-initialized

Solution 3

No. There is no automatic initialization in C++. Your new bool will be "initialized" to whatever was in memory at that moment, which is more likely to be true (since any non-zero value is true), but there is no guarantee either way.

You might get lucky and use a compiler that plays nice with you and will always assign a false value to a new bool, but that would be compiler dependent and not based on any language standard.

You should always initialize your variables.

Share:
10,783
WilliamKF
Author by

WilliamKF

Updated on July 17, 2022

Comments

  • WilliamKF
    WilliamKF almost 2 years

    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.)