I need to initialize a boost::shared_ptr based on a condition. Sample code is below that depicts the scenario i ma looking for.
class A{};
class B:public A{};
class C:public A();
void some_func(int opt)
{
boost::shared_ptr<A> abstract_ptr;
if(opt==RELEVENT_TO_B)
{
abstract_ptr(new B);
}
else
{
abstract_ptr(new C);
}
}
I know, above code sample is wrong. boost::shared_ptr<A> Abstract_ptr in second line of some_func() will create a shared_ptr object with the shared_ptr constrcutor that takes no arguments and since there is no assignment operator defined and no shared_ptr takes raw pointer after initialization so code within if-else is wrong.
My question is, how i can achieve this (conditional initialization as shown in some_func) modestly with boost::shared_ptr.
You could use
.reset()to put a raw pointer to the shared pointer.You could also directly assign a shared ptr to it: