以下是使用const_cast未定义的行为? [英] Is the following use of const_cast undefined behavior?

查看:98
本文介绍了以下是使用const_cast未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个语言律师问题,不是一个好的习惯问题。

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

以下代码是有效还是未定义的行为?一个const对象最后调用一个非const函数,但它并不实际修改对象的状态。

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


推荐答案

C ++标准,第5.2.11节/第7节[const cast]

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


[注意:根据对象的类型,通过指向const_cast的指针,值或指针到数据成员写操作限定符可能会产生未定义的行为。 -end note]

[ 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() code> Bob ,因此此程式不涉及未定义的行为。

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

这篇关于以下是使用const_cast未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆