Reputation: 156
I am in a situation where I need to make a shared_ptr
either null
or contain an instance of class Bar
.
The approach below does not work though since, Bar
and nullptr
are not of the same type. How can achieve this?
class Bar {};
class Foo {
private:
shared_ptr<Bar> b;
public:
Foo() : b(true ? Bar() : nullptr) {
}
};
Upvotes: 4
Views: 318
Reputation: 28987
Your problem is that your initialization of b
is incorrect.
b(Bar())
won't compile either. You'd need
b(new Bar())
and the equivalent with the ternary operator:
b(true?new Bar():nullptr)
is fine. However, I would recommend avoiding naked new
wherever possible, and use
b(true?maked_shared<Bar>():nullptr)
Although make_shared
returns a different type to nullptr
, they can be coerced into the same type by constructing an empty shared_ptr
from the nullptr
Upvotes: 0
Reputation: 206607
You can use
Foo() : b(true ? std::make_shared<Bar>() : nullptr) {}
My suggestion will be to push that logic to a helper function.
class Foo {
private:
std::shared_ptr<Bar> b;
static std::shared_ptr<Bar> getB(bool flag)
{
return (flag ? std::make_shared<Bar>() : nullptr);
}
public:
Foo() : b(getB(true)) {}
};
Upvotes: 1