Re: Should the shared_ptr have release method?
Thiago Adams wrote:
The custon deleter is is a very interesting solution!!
But we also need to create a very specialized code. In this case, maybe
is better to create the "vector_builder" (it is more efficient). I
don't know if is possible to create an adapter to use the auto_ptr
inside STL containers? Something likes the CAdapt from ATL for
auto_ptr.
We need take care about the weak_ptr's as well.
To handle weak_ptrs correctly, ItemPtr::release() just has to combine a
few operations, namely: to assume ownership of the shared_ptr's
pointer, reset the shared_ptr, and return the emancipated pointer to
the caller. Once these changes are made, the weak_ptr problem is
solved.
To implement this solution, first add a get_weak_ptr() method to
ItemPtr:
weak_ptr<Item>
ItemPtr::get_weak_ptr() const
{
return weak_ptr<Item>(ptr_);
}
Now implement the ItemPtr::release() method:
Item* ItemPtr::release()
{
if (not ptr_.unique())
throw std::runtime_error("released ptr not unique");
Item * p = ptr_.get();
std::tr1::get_deleter<released_deleter>( ptr_)->release();
ptr_.reset();
return p;
}
And finally run this revised main() to try out this new design:
int main()
{
vector<ItemPtr> v;
v.push_back( ItemPtr(1) );
weak_ptr<Item> wp = v.front().get_weak_ptr();
std::cout << "weak_ptr expired: ";
std::cout << std::boolalpha << wp.expired() << "\n";
vector< Item* > v2( v.size() );
transform( v.begin(), v.end(), v2.begin(),
mem_fun_ref( &ItemPtr::release ));
std::cout << "weak_ptr expired: ";
std::cout << std::boolalpha << wp.expired() << "\n";
v.clear();
}
Program Output:
weak_ptr expired: false
not deleting Item
weak_ptr expired: true
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]