Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const with smart pointers in C++

I'm writing a smart pointer implementation in C++, and I'm having some trouble with const-correctness. Below is an excerpt from the code:

template <class T> class Pointer {
  T* pointee;

public:  

  Pointer(const Pointer<T>& other) { // must be const Pointer& for assignments
    pointee = other.getPointee();
  }

  T* getPointee() const {
    return pointee;
  }
};

This is one way to do it, however I feel uneasy the const member not returning a const pointer. Another possibility would be to let getPointee() return a const T* and perform a const_cast<T*> in the copy constructor.

Is there a better way of doing this? If not, which do you think to be the lesser evil, returning a non-const or doing a const_cast?

like image 625
lucas clemente Avatar asked Dec 03 '25 19:12

lucas clemente


2 Answers

Best to think of your constant smart pointer as a constant pointer to a non-constant object. This is similar to:

int * const int_ptr;

If you wanted a pointer to a constant object:

Pointer<const int> const_int_smart_ptr;

which is basically equivalent to:

const int *const_int_ptr;
like image 136
zennehoy Avatar answered Dec 06 '25 08:12

zennehoy


The object designated by pointee doesn't seem to belong to Pointer, so I see no reason to assume that calling a const function of Pointer would return a T const*, rather than a T*. (If the pointed to object were conceptually part of Pointer, of course, the issue would be different.)

like image 24
James Kanze Avatar answered Dec 06 '25 09:12

James Kanze



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!