Re: Should the shared_ptr have release method?
In article <1167747311.118441.35630@v33g2000cwv.googlegroups.com>,
"Thiago Adams" <thiago.adams@gmail.com> wrote:
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);
}
I can't help you today. But there is a C++0X solution to your problem.
I'm presenting it here so that you know a solution is on the way.
Unfortunately you'll still have to work out a workaround until your
vendor comes up to speed. But know that adding a release function to
shared_ptr (which is also std in C++0X) may not be the best interim
workaround since by the time we get std::shared_ptr, we should also have
the functionality below:
std::vector<std::unique_ptr<Item>> func(int N)
{
std::vector<std::unique_ptr<Item>> local;
for (int i = 0; i < N, i++)
{
local.push_back(std::unique_ptr<Item>(new Item(i)));
}
return local;
}
At first glance you may look on this with horror: passing a vector
around by value?! Well, not really. This use of vector will either
elide the "copy" on return, or "move" it out. C++0X will be prohibited
from copying "local" out. That means that even if you have something
like:
vector<unique_ptr<Item>> v;
v = func(N);
It is guaranteed that new Item will only be called N times (inside of
func). And once local is fully constructed within func, no other
allocations take place.
Think of unique_ptr as the same thing as auto_ptr, just safe to put into
vector. It has unique ownership semantics, just like auto_ptr. It has
the same overhead as auto_ptr. It even has release().
And the func() outlined below has a strong exception safety guarantee.
If an exception is thrown while forming "local", nothing else is
affected, and "local" is completely cleaned up.
In the near future you will be able to pass vectors around "by value" in
many cases (such as the one above) without incurring an O(N) cost.
-Howard
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]