marsh
marsh

Reputation: 2730

Unique Pointer nullptr comparison

I have a simple AutoPtr class

template<typename T>
class AutoPtr
{
public:
    explicit AutoPtr(T* p = NULL):m_ptr(p){}
    ~AutoPtr()
    {
        if(m_ptr)
            delete m_ptr;
        m_ptr = NULL;
    }

    T&  operator*(){return *m_ptr;}
    T*  operator->(){return m_ptr;}
    T* Get()        { return m_ptr; }

private:
    T*    m_ptr;
};

How would I make this class usable for operations such as:

AutoPtr<MyClass> ptr;
if(ptr)
{
    // Do stuff!
}

I have tried

bool operator==(const T& other) { return m_ptr == other.m_ptr; }
bool operator!=(const T& other) { return !(*this == other);}

and

template<typename T>
bool operator==(const AutoPtr<T>& x, void* y) {  return x.Get() == y; }
template<typename T>
bool operator!=(const AutoPtr<T>& x, void* y) {  return x.Get() != y; }

This is not homework, I may not use c++11 or boost.

Upvotes: 1

Views: 163

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136296

There is a known idiom for implementing safe bool operator: https://en.wikibooks.org/wiki/More_C++_Idioms/Safe_bool

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 311028

You can define the operator the following way

explicit operator bool() const { return m_ptr != NULL; } 

If your compiler does not support specifier explicit then the other approach is to define operator

operator const void *() const { return m_ptr; }

In the last case you may use your class with operator <<

For example

std::cout << AutoPtr() << std::endl;

Upvotes: 2

Related Questions