|
Boost : |
Subject: Re: [boost] casting a shared_ptr from void with custom deleter
From: Christopher Currie (christopher_at_[hidden])
Date: 2009-03-20 13:04:11
On Fri, Mar 20, 2009 at 7:03 AM, Peter Dimov <pdimov_at_[hidden]> wrote:
> Kenny Riddile:
>>
>> I'm trying to do something like this:
>>
>> boost::shared_ptr<const Foo> fooPtr( boost::static_pointer_cast<const
>> Foo>(typeErasedFoo), CustomDeleter<const Foo>() );
>>
>> where typeErasedFoo is of type:
>>
>> boost::shared_ptr<const void>
Just to clarify Peter's point, deletion policy decisions should be
made at initialization time, not as a part of a type conversion. So,
your original object construction, which you don't show, should set
your custom deleter when you create the pointer that receives your
"new Foo".
A custom deleter is a part of the underlying "value" of the smart
pointer, and as such are preserved across casts, so there shouldn't be
a need for the kind of call you're trying to do. The code below
demonstrates what I mean:
#include <iostream>
#include <boost/shared_ptr.hpp>
struct Foo{};
struct FooDeleter{
void operator()( Foo* f ) {
std::cout << "Goodbye, cruel world!";
delete f;
}
};
int main() {
boost::shared_ptr<Foo> pFoo;
{
boost::shared_ptr<void> pVoid;
{
boost::shared_ptr<Foo> pTmp( new Foo, FooDeleter() );
pVoid = pTmp;
}
pFoo = boost::static_pointer_cast<Foo>( pVoid );
}
// emits "Goodbye, cruel world!" when pFoo is destructed.
}
Naturally, you don't have to use a shared_ptr<Foo> when you first
allocate the Foo object, it's perfectly valid for the pTmp variable to
be eliminated and simply declare: boost::shared_ptr<void> pVoid( new
Foo, FooDeleter() );
HTH,
Christopher
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk