Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
};
like image 607
waas1919 Avatar asked Jul 20 '15 09:07

waas1919


People also ask

What is constructor initialization list?

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.

How do you initialize a class pointer?

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 .

What is a shared pointer in C++?

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.

What is Make_shared in C++?

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.


1 Answers

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.

like image 108
BartoszKP Avatar answered Oct 13 '22 07:10

BartoszKP