Boost logo

Boost :

Subject: Re: [boost] Is there a way to specialize how a smart_ptr<T> releases the T?
From: David Abrahams (dave_at_[hidden])
Date: 2012-10-24 10:06:04


on Wed Oct 24 2012, David Hagood <david.hagood-AT-gmail.com> wrote:

> If shared_ptr defined a release function:
>
> template <typename T> class shared_ptr
> {
> ...
> void Release(T *t) { delete(t);}
> }
> and used Release where it currently deletes the object, then in a case
> like mine, all you'd have do to is specialize it:
>
> template <> shared_ptr<xmlDoc>::Release(xmlDoc *t) { xmlFreeDoc(t);}
>
> and then all shared_ptr<xmlDoc> would correctly release the object.

That actually wouldn't work. Consider that there's implicit upcasting
all the way to shared_ptr<void>

> I guess what I can do to avoid the risk would be to derive from
> shared_ptr and provide the destructor in my ctor.

The best way to do this is to wrap shared_ptr<xmlDoc> construction in a
function that creates the necessary deleter. Then, if you own xmlDoc,
you can even make its destructor private, which can prevent people from
dynamically allocating them any other way.

HTH,

-- 
Dave Abrahams
BoostPro Computing                  Software Development        Training
http://www.boostpro.com             Clang/LLVM/EDG Compilers  C++  Boost

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk