简体   繁体   中英

Is the following use of const_cast undefined behavior?

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();
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM