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?
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;
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With