17

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.
};
5
  • 2
    how is Bar declared? Commented Jul 20, 2015 at 9:36
  • 2
    I guess your Bar should have a constructor taking the callback. Commented Jul 20, 2015 at 9:36
  • I've edited with what Bar is..sorry:) Commented Jul 20, 2015 at 9:39
  • 4
    If you want Bar to be a POD type then you can use a {} braced list of values as initializer. An alternative C++03 way to keep Bar as POD type is define a derived class with constructor. Commented Jul 20, 2015 at 9:40
  • 2
    std::make_shared<Bar>(bar); actually calls a (implicitly defined) copy constructor, what is wrong with having a Bar instance as a member and call bar.m_callback = cb; in the constructor? Commented Jul 20, 2015 at 9:56

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ) )
{
    // ...
}

2 Comments

Sorry DevSolar.. I forgot to say that Bar was a struct. Question edited
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.