Re: Should the shared_ptr have release method?
Hi,
for me it looks like you're mixing motivations:
1) you wanna have a exception save function
2) you wanna have a container of items without shared pointers
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.
I don't see any relation to your aim. If the items c'tor throws an
exception you've to catch it otherwise your function couldn't be
exception safe for the user of this function.
May be you should consider implementing an initialization method to be
called for each newly created item to analyse the return value (error
code, simple: true/false). The item should not throw an exception
anymore then.
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 * >.
If you need - for any reason - a container of type
std::container<Item*> then see the example: (I'm using 'int' for
'Item')
- you've to make a copy of the items from the container of shared
items, if/when you're NOT sure about the life time of the two
containers. If both containers does have the same life time you just
need to copy the pointers ('csi[ix].get()' instead of 'new
int(*csi[ix])').
- of course you're responsible for deletion (when copied)
btw:
If someone decides to use a container with shared_ptr it's 100% not
good to remove ownership!
- - - example - - -
int main()
{
typedef vector<shared_ptr<int> > CSI;
typedef vector<int*> CI;
CSI csi;
CI ci;
int ix;
// init
for (ix = 0; ix < 10; ++ix)
csi.push_back(new int(ix));
// output
for (ix = 0; ix < 10; ++ix)
std::cout << *csi[ix] << std::endl;
// copy contents
for (ix = 0; ix < 10; ++ix)
ci.push_back(new int(*csi[ix]));
// output
for (ix = 0; ix < 10; ++ix)
std::cout << *ci[ix] << std::endl;
// cleanup
for (ix = 0; ix < 10; ++ix)
delete ci[ix];
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]