I was reading this question here here regarding const-correctness. The Scott Meyer solution seems like a good work-around, but what if you have a member function (which requires both a const and non-const version) that makes use of the this
pointer. If the member function is const
then this
automatically means const this
, which can make it difficult to have a single const
function where the bulk of the code lies.
One possible work-around that occurred to me was simply to pass a reference to this
to the const function as a parameter, so the function can use that reference instead of directly using the this
pointer. But, is this safe? It seems to be safe (if very hacky), because you're not actually using const_cast
on a const-object. Rather, you're simply circumventing the contract provided by the const
member function by passing it a non-const reference of the object.
For example:
class Foo
{
private:
template <class SelfReference>
void f1(SelfReference& self) const
{
// We now might have a non-const reference to "this", even though
// we're in a const member function. But is this safe???
}
public:
void f2()
{
f1(*this);
}
void f2() const
{
f1(*this);
}
};
This seems to provide a nice way to avoid having to duplicate large quantities of code when a const and non-const version of a function is required, but is this safe? Or does it cause undefined behavior somehow?