Can I depend on the fact that the new bool is initialized to false?

In C ++, can I depend on the fact that in all cases, false is initialized in all cases?

bool *myBool = new bool();

assert(false == *myBool);  // Always the case in a proper C++ implementation?

(Updated code to reflect comments.)

+5
source share
3 answers

In this case, yes; but the reason is pretty subtle.

The brackets in new bool()initialize the value, which initializes it as false. Without them new bool, it performs default initialization instead, which leaves it with an undefined value.

Personally, I’d better look new bool(false), if possible, so that it is clear that it should be initialized.

(, new , , , ).

: , , ; , , .

+6

, , bool , , bool false, bool bool false.

, . , . , , (), {}.

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

bool, .

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

, , - bool , , , .

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

No. In C ++, there is no automatic initialization. Your new bool will be β€œinitialized” with what was in memory at that moment, which is likely to be true (since any non-zero value is true), but there is no guarantee in any case.

You may be lucky and use a compiler that plays well with you and will always assign a false value to the new bool, but it depends on the compiler and does not depend on any locale.

You should always initialize your variables.

+2
source

All Articles