简体   繁体   English

以下是使用const_cast未定义的行为吗?

[英]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. const对象最终调用非const函数,但它实际上并不修改对象的状态。

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] C ++标准,第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. [注意:根据对象的类型,通过指针,左值或指向数据成员的指针的写入操作会导致const-qualifier的const_cast,这可能会产生未定义的行为。 —end note ] - 尾注]

GetA() does not write any member of Bob , so this program does not involve undefined behavior. GetA()不会写任何Bob成员,因此该程序不涉及未定义的行为。

I believe it is well-defined, since the standard only ascribes undefined behaviour to modifying a const object. 我相信它是定义明确的,因为标准仅归因于修改 const对象的未定义行为。 C++11 quotes follow: C ++ 11引用如下:

[expr.const.cast] 5.2.11 §7 [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). [ 注意:根据对象的类型,通过指针,左值或指向数据成员的指针的写入操作会导致const-qualifier的const_cast产生未定义的行为(7.1.6.1)。 —end note ] - 尾注 ]

[dcl.type.cv] 7.1.6.1 §4 [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. 除了可以修改声明为mutable (7.1.1)的任何类成员之外,任何在其生命周期内修改const对象的尝试(3.8)都会导致未定义的行为。 ... ...

GetA() does not actually modify any object, so it doesn't have undefined behaviour. GetA()实际上并没有修改任何对象,因此它没有未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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