Search code examples
c++constructorunique-ptr

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?


Solution

  • 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.