Aviv Cohn
Aviv Cohn

Reputation: 17243

How can I define a function that takes as a parameter a pointer value of any kind?

I'm implementing for practice a smart pointer class.

I already defined an assignment operator overload that takes another instance of the same class. Now I want to define an overload of this operator, that takes any pointer. So I should be able to do stuff like smartPointer = &someObject; or smartPointer = NULL;, etc.

How can I go about doing that? Should I pass in a void*? Something else?

As a more general question (and I know this is rarely desired): what kind of parameter tells the compiler that any pointer can be passed in?

Upvotes: 0

Views: 66

Answers (2)

Jarod42
Jarod42

Reputation: 217810

Following may help:

class MySharedPointer
{
public:

    template <typename T>
    MySharedPointer& operator = (T* p)
    {
        ptr.reset(p, [](void* p) { delete static_cast<T*>(p); });
        return *this;
    }

    // nullptr is not a pointer, so it should have its own overload.
    MySharedPointer& operator = (std::nullptr_t) {
        ptr.reset();
        return *this;
    }

private:
    std::shared_ptr<void> ptr;
};

Live example

Upvotes: 1

Sayu Sekhar
Sayu Sekhar

Reputation: 169

You can use a template function to make your object allow any pointer to be assigned to it.

template<typename T>
void operator=(T* obj)
{
    //Your code here
}

However, its not a smart pointer if you could assign it any raw pointers as it could be assigned to more than one smart pointer object and then there would be a problem while deleting the pointer.

Upvotes: 1

Related Questions