Boost logo

Boost :

From: Preston A. Elder (prez_at_[hidden])
Date: 2006-01-01 05:24:01


Hey,

What does everyone think of a new smart pointer called deep_ptr.

This pointer would hold a unique pointer (only one copy at a time), but
provide convenient syntax to have a deep copy of the underlying data on an
operator= call.

A sample implementation would be something like:

template<typename T>
class deep_ptr
{
    typedef deep_ptr<T> this_type;

public:
    typedef T element_type;
    typedef T value_type;
    typedef T * pointer;
    typedef T & reference;

    deep_ptr() : px(NULL) {}
    deep_ptr(T * ptr) : px(ptr) {}
    deep_ptr(deep_ptr const & in) : px(new T(*in.px)) {}
    deep_ptr &operator=(deep_ptr const & in)
    {
        delete px;
        px = new T(*in.px);
    }
    ~deep_ptr() { delete px; }

    void reset()
    {
        this_type().swap(*this);
    }

    template<typename U>
    void reset(U * p)
    {
        BOOST_ASSERT(p == 0 || p != px);
        this_type(p).swap(*this);
    }

    reference operator* () const
    {
        BOOST_ASSERT(px != 0);
        return *px;
    }

    T * operator->() const
    {
        BOOST_ASSERT(px != 0);
        return px;
    }

    T * get() const
    {
        return px;
    }

    operator bool () const
    {
        return px != 0;
    }

    bool operator! () const
    {
        return px == 0;
    }

    void swap(deep_ptr<T> & other)
    {
        std::swap(px, other.px);
    }

private:
    T *px;
};

template<typename T, typename U>
inline bool operator==(deep_ptr<T> const & a, deep_ptr<U> const & b)
{
    return a.get() == b.get();
}

template<typename T, typename U>
inline bool operator!=(deep_ptr<T> const & a, deep_ptr<U> const & b)
{
    return a.get() != b.get();
}

template<typename T, typename U>
inline bool operator<(deep_ptr<T> const & a, deep_ptr<U> const & b)
{
    return a.get() < b.get();
}

template<class T>
inline void swap(deep_ptr<T> & a, deep_ptr<T> & b)
{
    a.swap(b);
}

This way, as I said, each copy would have its own version of the data, but
in a class that uses it, you would not then have to write your own
operator= for that class to handle the deep copy, you just make it use a
deep_ptr instead of a regular pointer.

I'll admit, its simply a case of adding syntactical sugar, but I could see
how this would become extremely useful :)

-- 
PreZ :)
Death is life's way of telling you you've been fired.
                -- R. Geis

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk