Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it UB to call a non-const method on const instance when the method does not modify members? [duplicate]

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 bars 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.

like image 282
463035818_is_not_a_number Avatar asked Oct 01 '19 15:10

463035818_is_not_a_number


2 Answers

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.

like image 137
Bathsheba Avatar answered Sep 23 '22 18:09

Bathsheba


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).

like image 26
Mark B Avatar answered Sep 22 '22 18:09

Mark B