Reputation: 562
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.
Upvotes: 1
Views: 909
Reputation: 24124
Wouldn't this work?
void some_func(int opt)
{
boost::shared_ptr<A> abstract_ptr((opt == RELEVENT_TO_B) ? (A*) new B ? (A*) new C));
}
Upvotes: 0
Reputation: 69967
Firstly, it isn't a problem to do what you do already, i.e. reassigning the shared pointer:
boost::shared_ptr<A> abstract_ptr;
if(opt==RELEVENT_TO_B)
abstract_ptr = boost::make_shared<B>();
else
abstract_ptr = boost::make_shared<C>();
The effect of the first line above is that a null-pointer is wrapped in the shared pointer, and the effect of a re-assignment is that the reference count of the currently wrapped object is decremented, and that of the newly assigned object is incremented. No problems there.
Alternatively, if you want to keep it all on one line, you could use the conditional operator:
boost::shared_ptr<A> abstract_ptr = (opt==RELEVANT_TO_B ? boost::make_shared<B>() : boost::make_shared<C>());
Upvotes: 1
Reputation: 523214
You could use .reset()
to put a raw pointer to the shared pointer.
boost::shared_ptr<A> abstract_ptr;
if (opt == RELEVENT_TO_B)
abstract_ptr.reset(new B);
else
abstract_ptr.reset(new C);
You could also directly assign a shared ptr to it:
boost::shared_ptr<A> abstract_ptr;
if (opt == RELEVENT_TO_B)
abstract_ptr = boost::make_shared<B>();
else
abstract_ptr = boost::make_shared<C>();
Upvotes: 3