Search code examples
boostshared-ptr

const shared_ptr to shared_ptr


How can one convert a shared_ptr that points to a const object to a shared_ptr that points to a non-const object. I am trying to do the following :

boost::shared_ptr<const A> Ckk(new A(4));

boost::shared_ptr<A> kk=const_cast< boost::shared_ptr<A> > Ckk;

But it does not work.


Solution

  • 'boost::const_pointer_cast' will do what you're asking for, but the obligatory second half of the answer is that you probably shouldn't use it. 99% of the time when it seems like you need to cast away the const property of a variable, it means that you have a design flaw. Const is sometimes more than just window dressing and casting it away may lead to unexpected bugs.

    Without knowing more details of your situation one can't say for certain. But no discussion of const-cast is complete without mentioning this fact.