Search code examples
c++constantsmutability

How to make a pointer member data's constness vary with the parent instance's constness?


I have a class like this one:

struct Example
{
    std::unique_ptr<int> pointer_member;
};

I'd like the type of pointer_member to be std::unique_ptr<int const> const when manipulating instances of Example const, and std::unique_ptr<int> when manipulating instances of Example.

The best solution I could think of so far involves templates, but it's really boilerplaty and not very usable (because the template arguments propagate to the code working with Example):

template <bool is_const>
struct Example
{
    std::unique_ptr<std::conditional_t<is_const, int const, int>> pointer_member;
};

Also here, nothing prevents me from using Example<false> const instances and it's really annoying.

Any idea of how to achieve this in a better way?


Solution

  • Encapsulation allows to control modifiable-ness (aka constness) of members:

    #include <memory>
    struct Example {
        const int& get() const {
            return *pointer_member;
        }
        int& get() {
            return *pointer_member;
        }
    private:
        std::unique_ptr<int> pointer_member = std::make_unique<int>(42);
    };
    
    
    int main(){
        const Example ex1;
        const int& const_ref = ex1.get();
        Example ex2;
        ex2.get() = 123;
    }