Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 493
gruszczy Avatar asked Oct 31 '25 16:10

gruszczy


1 Answers

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.

like image 74
songyuanyao Avatar answered Nov 02 '25 07:11

songyuanyao