Boost logo

Boost :

From: David B. Held (dheld_at_[hidden])
Date: 2002-09-02 19:31:27


I just wrote this little utility function, and wondered if it is generally
useful.

    // Requirements:
    // Ptr must define element_type
    // Ptr::element_type must be default-constructible
    template <class Ptr>
    typename Ptr::element_type const& safe_dereference(Ptr p)
    {
        return p ? *p : typename Ptr::element_type();
    }

    // Requirements:
    // T must be default-constructible
    template <typename T>
    T const& safe_dereference(T* p)
    {
        return p ? *p : T();
    }

In my use case, I am storing shared_ptrs which may or may not actually
point to something. I want to be able to dereference it regardless, and
just get a default value when the pointer is null (which should be obvious
enough from the code). Here's a sample usage:

class some_data
{
public:
    other_data const& optional_member(void) const
    { return safe_dereference(optional_member_); }
private:
    boost::shared_ptr<other_data> optional_member_;
};

some_data::optional_member() will always succeed, but will just return
a default value for a null pointer, which is memory-cheaper than
constructing a default value, and pointing to it (unless, I suppose, there
were a "central" default value that everyone pointed to, but that seems
a bit odd).

Dave


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