const_cast 与可变和未定义的行为

问题描述 投票:0回答:1
#include <iostream>

struct Foo {
    Foo(const int a) : total(a) {}

    int       index = 0;
    const int total;
};

struct Bar {
    Bar(const int a) : total(a) {}

    mutable int index = 0;
    const int   total;
};

int main() {
    const Foo* const foo = new Foo(3);
    for (
        ;
        foo->index < foo->total;
        const_cast<Foo*>(foo)->index++ // 1. Undefined behavior because foo is const
    )
        std::cout << "Foo " << foo->index << std::endl;

    const Bar* const bar = new Bar(3);
    for (
        ;
        bar->index < bar->total;
        bar->index++ // 2. Not undefined behavior because of mutable?
    )
        std::cout << "Bar " << bar->index << std::endl;

    return 0;
}

据我所知,标有

// 1. Undefined behavior because foo is const
的行是未定义的行为,因为
foo
是一个
const
对象,并且
const_cast
无论如何都被用来修改该对象

但是我不确定是否存在与标有

// 2. Not undefined behavior because of mutable?
的行相关的任何可能的未定义行为。它本质上是通过使用
mutable
而不是
const_cast

来实现相同的结果

我的问题是,在某些情况下,具有

const
成员的
mutable
对象是否会导致未定义的行为

c++ undefined-behavior mutable const-cast
1个回答
0
投票

A

mutable
字段永远不是 const,因此永远不能使用 const_cast 调用 UB。这不是相同的行为,因为理论上#1 可以将索引放置在 rom 中

© www.soinside.com 2019 - 2024. All rights reserved.