Reputation: 6389
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
?
Upvotes: 2
Views: 3218
Reputation: 153909
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.)
Upvotes: 4
Reputation: 6846
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;
Upvotes: 8