Console with an empty base class

Is the undefined behavior for const_cast an empty base class and calls the non const method on it? for instance

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

I could not find the relevant information in the standards (C ++ 14 and C ++ 17) that responds to this.

+5
source share
1 answer

This is not UB in itself. You get undefined behavior when you drop a constant and use the resulting glvalue to modify the object that was originally declared const. Here's the standard quote ( [dcl.type.cv] / 4 ):

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

A simple call to a member function is not a modification of an object. It all depends on what the function does. So if he does something crazy, like:

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

This will lead to undefined behavior, of course. But if we assume that this is not so, and since there are no members to change it in an incorrectly formed form, UB will not be called.

Another question, whether he has a good idea, has an obvious answer. Consoles should not clog code bases. But if the base class behaves well, although it is not clearly defined, it may be acceptable if you cannot change the class.
+7
source

Source: https://habr.com/ru/post/1274243/


All Articles