Boost logo

Boost :

From: Joe Gottman (jgottman_at_[hidden])
Date: 2006-03-18 08:05:08


"Daniel Frey" <d.frey_at_[hidden]> wrote in message
news:dvghr5$j1j$1_at_sea.gmane.org...
> 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)?

   I think you should use a shared_array here.
shared_array<char *> p(( ::backtrace_symbols(addr,n), &::free );

Joe Gottman


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