Re: Should the shared_ptr have release method?
Howard Hinnant wrote:
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:
Yes, I agree. I think that the release function in shared_ptr is not
necessary considering the existence of the unique_ptr.
The solution using moving semantics is really elegant.
I had one more idea to implement this function. The auto_ptr solves the
exception safe problem for one item very well. All we need is to solve
the problem for N items.
So, I have tested a recursive functions to create N auto_ptrs and it
works fine. I am now trying to generalize this recursive functions to
be used as an algorithm to create/insert objects into containers.
(Maybe this solution is efficient as well)
struct Item
{
int i;
Item(int i) : i(i)
{
cout << "constructing item " << i << endl;
if (i == 5) throw std::exception("Exception to test fail");
}
~Item()
{
cout << "destroying item " << i << endl;
}
};
void CreateItem(vector<Item*> & vec, int & n)
{
if (n == 10)
return;
auto_ptr<Item> ap(new Item(n));
vec.push_back(ap.get());
n++;
CreateItem(vec, n);
ap.release();
}
void GetItems(vector<Item*> &vec)
{
vector<Item*> local;
int i = 0;
CreateItem(local, i);
local.swap(vec);
}
int main()
{
vector<Item*> items;
try
{
GetItems(items);
vector<Item*>::iterator it = items.begin();
for( ; it != items.end(); ++it)
delete *it;
}
catch(const std::exception & e)
{
cout << e.what();
}
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]