当方法不修改成员时,在const实例上调用非const方法是否为UB? [英] Is it UB to call a non-const method on const instance when the method does not modify members?
问题描述
代码说出一千多个单词,所以...
Code speaks more than thousand words, so...
这是对 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方法对象(通过 const_cast
)在方法不使对象发生突变时?
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 :我知道 no_modify
应该已经声明为 const
,然后这个问题毫无意义,但是假设 bar
的定义无法更改。
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 :只需确定:不要在家里(或其他任何地方)。我绝不会让这样的代码通过审查。可以轻松避免强制转换。这是一个语言律师问题。
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.
推荐答案
代码的行为已明确定义。
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.
这篇关于当方法不修改成员时,在const实例上调用非const方法是否为UB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!