Question

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;
};
  1. What is the purpose of the first public function in the API?
  2. Why do we need to const-overload the other two API methods?
  3. Not only const-overload, but why have return-const-object variants?
Was it helpful?

Solution

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.

OTHER TIPS

The conversion operator looks to be intended to do two things:

  1. Convert the smart pointer to void*. Generally pointers convert to void* but I'm not sure whether it is a good idea to do for smart pointers.
  2. It will be used when testing objects to see what value they have when evaluated in a boolean context. That can be used to determine if the pointer is a null pointer.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top