How to initialize a generic pointer in a constructor initialization list?

How to initialize a generic pointer in a constructor initialization list?

I have it:

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

    //...
}

I would like to put this on the list of constructor initializers. Sort of:

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

A bar is struct:

struct Bar
{
  callback_type m_callback;
  // etc.
};
+4
source share
2 answers

Add a constructor explicit Bar::Bar(const callback&). explicitprevent errors associated with automatic conversion.

Even better, if it Baris an aggregate, you can use a parenthesis initializer:

Foo::Foo(const callback& cb)
  : m_ptr(std::make_shared<Bar>(Bar{cb}))
+5

The constructor implementation Bar::Bar( const callback & )will be the obvious solution ...?!?

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

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


All Articles