Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to preserve const correctness across pointers?

Tags:

c++

constants

I am trying to have a const operation on a class that is truly const - it does not change data that the class points to.

For example:

class Node{
public:
    int val;
};
class V{
public:
    Node * node; //what is the change that is needed here?
    void const_action()const{
        node->val=5; //error wanted here
    }
    void action(){
        node->val=5; //error is not wanted here
    }
};
like image 218
yigal Avatar asked Jan 11 '14 17:01

yigal


1 Answers

You can use a template to enforce the const correctness on a pointer without changing the meaning or the implementation of your class:

    template <typename T>
class PreseveConstPointer
{
    T *t_;
public:
    PreseveConstPointer(T *t = nullptr)
        : t_(t)
    {
    }
    PreseveConstPointer<T> * operator=(T *t)
    {
        t_ = t;
        return this;
    }
    T* operator->()
    {
        return t_;
    }
    T const * operator->() const
    {
        return t_;
    }
    T * data()
    {
        return t_;
    }
};
class Node{
public:
    int val;
};
class V{
public:
    PreseveConstPointer<Node> node;
    V()
    {
        node = new Node;
    }
    ~V()
    {
        if(node.data())
            delete node.data();
    }
    void const_action()const{
        node->val=5; // You will get an error here
    }
    void action(){
        node->val=5; // No error here
    }
};
like image 88
Sebastian Cabot Avatar answered Nov 10 '22 00:11

Sebastian Cabot