有条件地将初始值设定项列表中的shared_ptr设为 null



我需要null或包含类Bar实例进行shared_ptr的情况。

下面的方法不起作用,因为Barnullptr不属于同一类型。如何实现这一目标?

 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来强制转换为相同的类型

最新更新