当方法不修改成员时,在const实例上调用非const方法是否为UB?

for*_*818 6 c++ const const-cast language-lawyer

代码说出了上千个单词,所以...

这是使a发生突变的未定义行为const int

struct foo {
    int x;
    void modify() { x = 3; }
};

void test_foo(const foo& f) {
    const_cast<foo&>(f).modify();
}

int main(){
    const foo f{2};
    test_foo(f);
}
Run Code Online (Sandbox Code Playgroud)

那这个呢:

struct bar {
    void no_modify() { }
};

void test_bar(const bar& b) {
    const_cast<bar&>(b).no_modify();
}

int main(){
    const bar b;
    test_bar(b);
}
Run Code Online (Sandbox Code Playgroud)

const_cast当方法不改变对象时,是否可以通过const对象调用非const方法?

PS:我知道no_modify应该将其声明为const,然后这个问题毫无意义,但假设bars的定义不能更改。

PPS:只需确保:不要在家中(或其他任何地方)这样做。我绝不会让这样的代码通过审查。可以轻松避免强制转换。这是一个语言律师问题。

Bat*_*eba 4

您的代码的行为是明确定义的。

唯一重要的是您是否实际修改了该对象。你不知道。您所做的只是调用成员函数,并且该函数不会修改对象。

  • 请注意,这被标记为语言律师问题。 (6认同)

归档时间:

查看次数:

144 次

最近记录:

6 年,2 月 前