我需要null
或包含类Bar
实例进行shared_ptr
的情况。
下面的方法不起作用,因为Bar
和nullptr
不属于同一类型。如何实现这一目标?
class Bar {};
class Foo {
private:
shared_ptr<Bar> b;
public:
Foo() : b(true ? Bar() : nullptr) {
}
};
b(true ? std::make_shared<Bar>() : nullptr)
您可以使用
Foo() : b(true ? std::make_shared<Bar>() : nullptr) {}
我的建议是将该逻辑推送到帮助程序函数。
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)) {}
};
您的问题是您对b
的初始化不正确。
b(Bar())
也不会编译。 你需要
b(new Bar())
与三元运算符等效:
b(true?new Bar():nullptr)
很好。 但是,我建议尽可能避免裸new
,并使用
b(true?maked_shared<Bar>():nullptr)
虽然make_shared
返回一个不同的类型给nullptr
,但它们可以通过从nullptr
构造一个空shared_ptr
来强制转换为相同的类型