gruszczy
gruszczy

Reputation: 42188

Do I need to explicitly initialize a std::unique_ptr in the constructor?

I have a class where one of the fields is std::unique_ptr<SomeClass>. This field is initially unset when the parent class object is constructed. Do I need to do:

field_(nullptr)

Or will this field get initialized automatically to the default value and will that be null?

Upvotes: 4

Views: 3519

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

No, you don't need it. The default constructor of std::unique_ptr will construct a std::unique_ptr owning nothing. The effect is same as initializing as field_(nullptr) explicitly.

Constructs a std::unique_ptr that owns nothing. Value-initializes the stored pointer and the stored deleter.

Upvotes: 7

Related Questions