Marodian
Marodian

Reputation: 539

Setting shared ptrs to null

Say i have a class Character and I have:

shared_ptr<Character> c;

As a field in class A. In the constructor of A, can I do this:

A::A(..):c{nullptr}

Is this valid? How do I properly initialize a shared ptr in MIL then?

Upvotes: 0

Views: 645

Answers (4)

eerorika
eerorika

Reputation: 238311

Setting shared ptrs to null

c{nullptr}

Is this valid?

Yes. That will call the shared_ptr(std::nullptr_t) constructor.

Other possibility is value initialization, which calls the default constructor: c().

Or simply don't have an entry in the member initialization list. Members that lack entry in the member initialization list and don't have a brace-initializer are default initialized. Default initialized class objects are initialized with the default constructor. Then, you don't need to have a user defined constructor at all. The implicitly generated one default initializes all members, which may be exactly what you want.

Upvotes: 2

Mark Ingram
Mark Ingram

Reputation: 73605

Just use empty braces:

A::A() :
c()
{
}

This will default initialise the instance.

Or forgo the initialisation completely.

A::A() = default or just delete the constructor completely.

Upvotes: 1

Slava
Slava

Reputation: 44238

Is this valid? How do I properly initialize a shared ptr in MIL then?

Yes as stated in documentation initializing std::shared_ptr by nullptr is prefectly valid. Note you can achieve the same using default constructor, but if you find this way more readable it initializes std::shared_ptr the same way:

1-2) Constructs a shared_ptr with no managed object, i.e. empty shared_ptr

Upvotes: 3

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

There is no need even to explicitly set c to nullptr, though your code is valid.

Here you might see a list of available constructors. Constructors:

constexpr shared_ptr() noexcept;
constexpr shared_ptr( std::nullptr_t ) noexcept;

do the same thing:

Constructs a shared_ptr with no managed object, i.e. empty shared_ptr

so default initialization of c is pretty good and should work for you too.

Upvotes: 4

Related Questions