views:

329

answers:

3

Hello

How to convert shared_ptr that points to const object to shared_ptr that point to nonconst 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 doesnot work.

+4  A: 

use boost::const_pointer_cast, documentation.

Nikola Smiljanić
A: 

the proper way should be this

boost::shared_ptr<A> kk (boost::const_pointer_cast<A>(Ckk));
YeenFei
+6  A: 

'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.

Alan
+1 that const is there for a reason. maybe.
George