Should the shared_ptr have release method?
In the boost site there is an FAQ answering why the shared_ptr
doesn't have the release method.
http://www.boost.org/libs/smart_ptr/shared_ptr.htm#FAQ
In general I think that the shared_ptr is not a tool just to
"share" pointers, but it is very useful to simplify the
implementations of exceptions safe functions.
The Motivation for "release()" method.
I want to return a vector of pointers of the type "Item". The
object "Item" can throw exceptions in constructor and I am trying to
create an exception safe function.
There are many ways to implement it, but actually I didn't find an
elegant way to do this.
The simple way is using two vectors of shared_ptr.
void (vector< shared_ptr<Item> > &vec)
{
vector< shared_ptr <Item> > local;
for (int i = 0; i < N, i++)
{
local.push_back(shared_ptr<Item> (new Item(i) ) );
}
local.swap(vec);
}
However, I think I should not penalize the caller to use a vector of
shared_ptrs, because the caller doesn't share pointers with anyone
else, and the simple RAII is enough. In top of that, sometimes the
caller needs to use Item * instead a vector<Item*> because it was
transferring data using C api. (For instance transferring buffers using
&vec[0])
So, what I need is to implement a function to swap between vector<
shared_ptr<Item> and vector< Item * >.
To create this function I need to remove ownership of shared_ptrs and
transfer to vector< Item * >. It is impossible because the shared_ptr
doesn't have release.
The questions are:
Should the shared_ptr have release method that works only if
use_count() == 1, and throws if use_count() > 1 ?
Am I using the wrong approach? There is a different smart pointer for
this?
Should we create a custom container to deal with this kind o problem?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]