Is the following use of const_cast undefined behavior?

落爺英雄遲暮 提交于 2019-12-19 00:57:23

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25406818/is-the-following-use-of-const-cast-undefined-behavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!