Boost logo

Boost :

From: Anthony Williams (anthwil_at_[hidden])
Date: 2002-09-04 03:36:52


David B. Held writes:
> 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).

I can see the point, but this is undefined behaviour --- you are returning a
reference to a temporary, which as gone out of scope.

Anthony


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