views:

140

answers:

2

I want to cast the const-ness out of a boost::shared_ptr, but I boost::const_pointer_cast is not the answer. boost::const_pointer_cast wants a const boost::shared_ptr, not a boost::shared_ptr. Let's forego the obligitory 'you shouldn't be doing that'. I know... but I need to do it... so what's the best/easiest way to do it?

For clarity sake:

boost::shared_ptr<const T> orig_ptr( new T() );

boost::shared_ptr<T> new_ptr = magic_incantation(orig_ptr);

I need to know the magic_incantation()

Thanks!

+5  A: 

boost::const_pointer_cast is the function you want to use:

boost::shared_ptr<const int> ci(new int(42));
boost::shared_ptr<int> i(boost::const_pointer_cast<int>(ci));

Does that not work for you? I tested that with both Boost 1.43 and the Visual C++2010 C++0x implementation--no issues with either.

James McNellis
Actually... it did work for me when I specified the template parameter. For some reason when I did it the first time I didn't use it and was then fooled by the compiler's error message. Thanks.
Flevine
@Flevine: Yeah, `const_pointer_cast`, like the C++ `const_cast`, can add or remove both const and volatile qualifiers, so the desired target qualification isn't known without specifying it. I'm glad to have helped.
James McNellis
A: 

Note that other "shareholders" will be very surprised, to say the least, if a shared const T suddenly changes...

FredOverflow