Boost logo

Boost :

From: Daniel Frey (d.frey_at_[hidden])
Date: 2006-03-18 03:53:56


Hello Boosters,

haven't found whether or not this was proposed before, so here we go:
What about adding an operator[] to shared_ptr:

[...]

#include <cstddef> // for std::size_t

[...]

// e.g. below operator*

reference operator[] (std::size_t index) const // never throws
{
    BOOST_ASSERT(px != 0);
    return px[index];
}

[...]

This makes it easier to wrap memory from system calls:

Before:

char** sym = ::backtrace_symbols(addr,n);

   // Lots of code here
   sym[0]; // access sym by index

::free(sym); // could be forgotten, code in between could throw, ...

After:

shared_ptr< char* > p( ::backtrace_symbols(addr,n), &::free );

   // Lots of code here, allowed to throw now :)
   sym[0]; // still access by index, no funny syntax needed

// no need to call ::free explicitly :)

Hope you get the idea :)

What do you think? Any problem with adding operator[] to make it more
similar to a plain old C-pointer (while still being safe AFAICT)?

Regards, Daniel


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