16

How can I initialize a shared pointer in the initialization list of a constructor?

I have this:

Foo::Foo (const callback &cb)
{
    Bar bar;
    bar.m_callback = cb;
    m_ptr = std::make_shared<Bar>(bar);

    //...
}

I would like to put this into the initializer list of the contructor. Something like:

Foo::Foo (const callback &cb) :
   m_ptr(std::make_shared<Bar>(?????))
{
  // ...
}

Bar is a struct:

struct Bar
{
  callback_type m_callback;
  // etc.
};
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
waas1919
  • 2,365
  • 7
  • 44
  • 76

2 Answers2

15

Add a constructor explicit Bar::Bar(const callback&). explicit will prevent mistakes related to automatic conversion. Then you can initialize a shared_ptr<Bar> like this:

Foo::Foo(const callback& cb)
  : m_ptr(std::make_shared<Bar>(cb))

See documentation for make_shared here.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
4

Implementing a constructor Bar::Bar( const callback & ) would be the obvious solution...?!?

Foo::Foo( const callback & cb ) :
   m_ptr( std::make_shared<Bar>( cb ) )
{
    // ...
}
DevSolar
  • 67,862
  • 21
  • 134
  • 209
  • Sorry DevSolar.. I forgot to say that Bar was a struct. Question edited – waas1919 Jul 20 '15 at 09:44
  • 3
    @waas1919: You *can* write constructors for `struct` too, you know... (At which point, the only difference between `struct` and `class` is the default visibility -- `private` for `class`, `public` for `struct`.) If you *need* to keep `Bar` a POD type, the comments by Alf and Piotr have alternatives. – DevSolar Jul 20 '15 at 09:57