I am reading through implementing smart pointers and I found the following code,
template <class T>
class SmartPtr
{
public:
explicit SmartPtr(T* pointee) : pointee_(pointee);
SmartPtr& operator=(const SmartPtr& other);
~SmartPtr();
T& operator*() const
{
...
return *pointee_;
}
T* operator->() const
{
...
return pointee_;
}
private:
T* pointee_;
...
};
I am not able to understand the following,
- “SmartPtr& operator=(const SmartPtr& other)”: why the parameter is constant? Doesn’t it lose its ownership when the assignment is done?
- And why do we need “T& operator*() const” and “T* operator->() const” methods?
Thx@
Point 1. Not necessarily, depends on the design of the smart pointer. Some like
boost:shared_ptrdo not transfer ownership on assignment.Point 2. Those methods simulate normal pointer operations on the smart pointer.