Conditionally make shared_ptr in the list of initializers null

I am in a situation where I need to do shared_ptreither nullor contain an instance of a class Bar.

The approach below does not work, because Barthey nullptrdo not have the same type. How can this be achieved?

 class Bar {};

 class Foo {

    private:
       shared_ptr<Bar> b;

    public:
       Foo() : b(true ? Bar() : nullptr) {
       }

 };
+4
source share
3 answers

b(true ? std::make_shared<Bar>() : nullptr)

+2

you can use

Foo() : b(true ? std::make_shared<Bar>() : nullptr) {}

My suggestion is to push this logic to an auxiliary 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)) {}

};
+1

, b .

b(Bar())

.

b(new Bar())

:

b(true?new Bar():nullptr)

. new, ,

b(true?maked_shared<Bar>():nullptr)

make_shared nullptr, , shared_ptr nullptr

0

Source: https://habr.com/ru/post/1694609/


All Articles