Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const casting empty base class

Is it undefined behavior to const_cast away an empty base class and call a non const method on it? For example

class EmptyBase {
public:
    void bar() { ... }
};

class Something : public EmptyBase {
public:
    void foo() const {
        const_cast<EmptyBase&>(static_cast<const EmptyBase&>(*this)).bar();
   }
};

I haven't been able to find relevant information in the standards (C++14 and C++17) that answers this..

like image 485
Curious Avatar asked Dec 21 '17 06:12

Curious


1 Answers

It's not UB in and of itself. You get undefined behavior when you cast away constness and use the obtained glvalue to modify an object which is originally declared const. Here's the standard quote on this ([dcl.type.cv]/4):

Except that any class member declared mutable can be modified, any attempt to modify a const object during its lifetime results in undefined behavior.

Merely calling a member function is not a modification of an object. It all depends on what the function does. So if it does something crazy like:

std::memset(this, 0, sizeof(*this));

That would result in undefined behavior, for sure. But assuming it doesn't, and since there are no members for it to modify in an ill-formed manner, there is no UB from the call.

The other question, of whether or not it's a good idea, has an obvious answer. Const casts should not litter code bases. But if the base class is well-behaved, albeit not well-defined, it may be acceptable if you can't change the class.

like image 74
StoryTeller - Unslander Monica Avatar answered Oct 26 '22 03:10

StoryTeller - Unslander Monica