See the following:
struct A
{
std::string* get() const
{
//return const_cast<std::string*>(&m_pObj);
return &const_cast<A*>(this)->m_pObj;
}
std::string m_pObj;
};
Is dereferencing const_cast of this UB? Is there any time dereferencing the result from const_casting the constness of a pointer away doesn’t invoke UB?
(I know the above example is bad practice, bad design, and could be solved with mutable – that’s not the point)
Not always, only if the object is const (the
Ainstance isconst A x;) and the dereference is used to modify the data. If it is only used to read it will not be undefined behavior, if the object is not const, (maybe not at all, maybe a const-reference to a non-const object) it won’t be UB either.