Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the following use of const_cast undefined behavior? [duplicate]

This is a language lawyer question, not a good practice question.

Is the following code valid or undefined behaviour? A const object ends up calling a non-const function, but it doesn't actually modify the state of the object.

struct Bob
{
    Bob() : a(0) {}

    int& GetA()
    {
        return a;
    }

    const int& GetA() const
    {
        return const_cast<Bob&>(*this).GetA();
    }

    int a;
};

int main()
{
    const Bob b;
    int a = b.GetA();
}
like image 983
Neil Kirk Avatar asked Aug 20 '14 14:08

Neil Kirk


2 Answers

The behavior is well-defined :

C++ standard, section § 5.2.11/7 [const cast]

[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior. —end note ]

GetA() does not write any member of Bob, so this program does not involve undefined behavior.

like image 58
quantdev Avatar answered Oct 02 '22 17:10

quantdev


I believe it is well-defined, since the standard only ascribes undefined behaviour to modifying a const object. C++11 quotes follow:

[expr.const.cast] 5.2.11 §7

[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier may produce undefined behavior (7.1.6.1). —end note ]

[dcl.type.cv] 7.1.6.1 §4

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

GetA() does not actually modify any object, so it doesn't have undefined behaviour.

like image 21
Angew is no longer proud of SO Avatar answered Oct 02 '22 15:10

Angew is no longer proud of SO