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

问题描述 投票:1回答:1

代码说出一千多个单词,所以...

这是使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);
}

这怎么办:

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

[当方法不使对象变型时,是否可以通过const对象调用非const方法?] [

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

c++ const language-lawyer const-cast
1个回答
0
投票

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

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

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