Aca Miln
Aca Miln

Reputation: 1

const_cast with bool: if condition ignored

VC++ 2010 problem:

const bool bNew = true;
const_cast<bool&>(bNew) = false;
if(bNew)//bNew is false here, but
{
    int i = 0;//this line will be executed
}

Why?

Thank you.

Upvotes: 0

Views: 392

Answers (1)

jamesdlin
jamesdlin

Reputation: 89995

From section 7.1.5.1/4 of the C++03 standard:

Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior.

You declared bNew to be a const object, then you undermined the type system by explicitly casting it away to modify it. You therefore invoked undefined behavior, which means that anything can happen.

Upvotes: 3

Related Questions