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.
};
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
You need to initialize a pointer by assigning it a valid address. This is normally done via the address-of operator ( & ). The address-of operator ( & ) operates on a variable, and returns the address of the variable. For example, if number is an int variable, &number returns the address of the variable number .
In C++, a shared pointer is one of the smart pointers. The shared pointer maintains a reference count which is incremented when another shared pointer points to the same object. So, when the reference count is equal to zero (i.e., no pointer points to this object), the object is destroyed.
std::make_sharedAllocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1). This function uses ::new to allocate storage for the object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With