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.
};
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 .
Implementing a constructor Bar::Bar( const callback & )
would be the obvious solution...?!?
Foo::Foo( const callback & cb ) :
m_ptr( std::make_shared<Bar>( cb ) )
{
// ...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.