std::unique_ptr<X> ptr;

Will ptr == nullptr return true for any type X ?

struct A {std::unique_ptr<X> ptr;}

A; A(); A{};

And in such cases for A.ptr ?

  • one
    I would like to know in connection with which the question arose. Did you get any unexpected results when compiling? - 伪位蔚蠂慰位蠀蟿

2 answers 2

The standard explicitly speaks of the default unique_ptr constructor:

2 Effects: Constructs the object and the deletion.
3 Postconditions: get() == nullptr . get_deleter() returns a reference to the stored deleter.

So yes.

As an example :

 struct A {std::unique_ptr<char> ptr;}; int main(int argc, const char * argv[]) { unique_ptr<int> x; cout << (x == nullptr) << endl; A a; A b{}; cout << (a.ptr == nullptr) << endl; cout << (b.ptr == nullptr) << endl; } 

    @Harry has already described how the default constructor for std::unique_ptr . I want to add that the type that has a constructor doesn鈥檛 matter how you define the variable:

     A a1; A a2 = A(); A a3 = A{}; 

    In all cases, the default constructor A will be invoked, which in this case will call the default constructor std::unique_ptr for the ptr member.

    Particular attention can be paid unless the records of the form:

     A a4(); A a5{}; 

    In the case of a4 , no object will be created, but there will be only a declaration of a function with the name a4 , which takes no arguments and returns type A In the case of a5 an object identical to a1 , a2 , a3 .

    About a4 can be found in more detail in the wiki: Most vexing parse .