Code speaks more than thousand words, so...
This is undefined behaviour for mutating 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);
}
What about this:
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);
}
Is it allowed to call a non-const method on a const object (via const_cast
) when the method does not mutate the object?
PS: I know that no_modify
should have been declared as const
and then the question is pointless, but assume bar
s definition cannot change.
PPS: Just do be sure: Dont do this at home (or anywhere else). I'd never let such code pass a review. The cast can be avoided trivially. This is a language-lawyer question.