[shared_ptr] Shall we add operator[]?

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

"Daniel Frey" <d.frey@gmx.de> wrote in message news:dvghr5$j1j$1@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

Joe Gottman wrote:
I think you should use a shared_array here. shared_array<char *> p(( ::backtrace_symbols(addr,n), &::free );
Doh! Of course! I just haven't looked at shared_array because I received a pointer from backtrace_symbols, which obviously means nothing in this case. Sorry for the noise and thanks! Regards, Daniel
participants (2)
-
Daniel Frey
-
Joe Gottman