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:只需确保:不要在家中(或其他任何地方)这样做。我绝不会让这样的代码通过审查。可以轻松避免强制转换。这是一个语言律师问题。
| 归档时间: |
|
| 查看次数: |
144 次 |
| 最近记录: |