独特的指针nullptr比较

时间:2015-03-04 18:54:59

标签: c++

我有一个简单的AutoPtr类

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;
};

如何使此类可用于以下操作:

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

我试过了

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

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; }

这不是作业,我可能不会使用c ++ 11或者提升。

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式定义运算符

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

如果您的编译器不支持说明符显式,那么另一种方法是定义运算符

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

在最后一种情况下,您可以将您的班级用于operator <<

例如

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

答案 1 :(得分:1)

实现安全bool运算符有一个已知的习惯用法:https://en.wikibooks.org/wiki/More_C++_Idioms/Safe_bool

相关问题