How to avoid repeated const and non-const virtual functions ? is it possible?

Viewed 152

Suppose I have a base class with the following function:

virtual int* get(){ return nullptr; }

and

I would like to supply a const version (bear in mind I have in ballpark of 50 different implementations in legacy code)

const int* get() const { return const_cast<decltype(this)>(this)->GetReturn(); };//NEED CODE BADLY: const_cast :/

But this idea needs to use a const_cast - scott meyer's suggest this approach in his book (albeit the situation is reversed) - but is it really safe (if yes, is it 'future-proof' as well?) from for example members being const ?

I can reverse the situation with some search/replace but having both implementations on all classes seems to be too much 'copy-paste' antipattern.

1 Answers

but is it really safe

Unfortunately not:

Variant 1:

class C
{
    int n;
public:
    int* get() { ++n; return &n; }
    int const* get() const { return const_cast<decltype(this)>(this)->get(); }
};

Variant 2:

class C
{
    int const n;
public:
    int const* get() const { return &n; }
    int* get() { return const_cast<int*>(const_cast<decltype(this) const*>(this)->get()); }
    void demo() // non-const!
    {
        ++*get();
    }
};

Admitted, the second case might not be too probable – but not impossible either. So in any of the two variants, there's an opportunity hidden to raise undefined behaviour...

Related