Reputation: 30645
I won't write all the code, but I am looking at a smart pointer example implementation and it has:
template<typename T>
class smart_ptr
{
public:
operator void*() const {return mPtr;}
const T& operator*() const;
T& operator*();
const T* operator->() const;
T* operator->();
private:
T* mPtr;
};
Upvotes: 2
Views: 562
Reputation: 29744
The operator void*
function is a type casting function, so you can write:
smart_ptr foo;
void* ptr = foo; // The compiler will call `operator void*` here
or even
if( foo) { // `operator void*` called to test boolean expression
//...
}
The functions
const T& operator*() const;
const T* operator->() const;
are const
, so you can call them on a const smart_ptr
. Because they return pointer/reference
to const
object, this object can't be changed.
Upvotes: 1
Reputation: 154025
The conversion operator looks to be intended to do two things:
void*
. Generally pointers convert to void*
but I'm not sure whether it is a good idea to do for smart pointers.Personally, I would probably only support the second use-case and use an explicit conversion to bool
instead:
explicit operator bool() const { return this->mPtr; }
The overloads for const
are obviously intended to propagate constness of the smart pointer to the pointed to objects.
Upvotes: 1