代码说出一千多个单词,所以...
这是使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
的定义不能更改。
代码的行为是明确定义的。
唯一重要的是是否实际修改了对象。你不知道您要做的只是调用一个成员函数。