Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Prevent changing pointer's value in const function

Take this dummy structure:

struct foo
{
    int* pI;
    void bar() const
    {
        int* ptrToI = pI; // I want this to require 'const int*'
        *ptrToI = 5; // I want this to fail
    }
}__test__;

How can I design this struct to prevent me from changing the value pI points to?

like image 844
KungPhoo Avatar asked Oct 23 '25 18:10

KungPhoo


1 Answers

You can use a custom smart pointer in order to hide the underlying pointer:

template <typename T>
struct ptr_t
{
private:
    T *ptr;
public:
    //Constructors and assignment operators
    ptr_t(): ptr(nullptr) {}
    ptr_t(T* p): ptr(p) {}
    ptr_t(const ptr_t &other): ptr(other.ptr) {}
    ptr_t& operator=(T* p) {this->ptr=p;return *this;}
    ptr_t& operator=(const ptr_t &other) {this->ptr=other.ptr; return *this;}

    //Note that the smart pointers included in the standard returns non-const pointers
    //That is why you need to define a custom smart pointer, which forces the const pointer return in the const version of the operators.
    const T* operator->() const {return ptr;}
    T* operator->() {return ptr;}
    const T& operator&() const {return *ptr;}
    T& operator&() {return *ptr;}

    operator const T*() const {return ptr;}
    operator T*() {return ptr;}
};

struct foo2
{
    ptr_t<int> pI;
    void nonconst_bar()
    {
        int* ptrToI = pI; // Now success, since not const
        *ptrToI = 5;
    }

    void failing_bar() const
    {
        //int* ptrToI = pI; // This fails
        //*pI = 5; // This also fails
    }

    void success_bar() const
    {
        const int* ptrToI = pI;
        //*ptrToI = 5; // This is not possible anymore
    }
};
like image 91
LoPiTaL Avatar answered Oct 26 '25 08:10

LoPiTaL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!