问题
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.
回答1:
The behaviour of your code is well-defined.
The only thing that matters is if you actually modify the object. You don't. All you do is call a member function, and that function does not modify the object.
回答2:
In the C++14 standard N4296 that I have access to we see a note in 5.2.11/6:
[ Note: Depending on the type of the object, a write operation through the pointer, lvalue or pointer to data member resulting from a const_cast that casts away a const-qualifier74 may produce undefined behavior (7.1.6.1). —end note ]
Technically I suspect the note may not be normative but it seems clear that the intention here is that casting away const-ness only becomes undefined behavior when a write is attempted through the pointer/reference (possibly to help support legacy code that didn't follow proper const-correctness).
来源:https://stackoverflow.com/questions/58187832/is-it-ub-to-call-a-non-const-method-on-const-instance-when-the-method-does-not-m