0
votes

I have one doubt in std::unique_ptr.

When we assign std::make_unique() having no arguments, What will happen?

For example,

struct A {
  int a, b;
  A() {}
  A(int w, int e) : a(w), b(e) {}
};

int main() {
   A h(1, 2);
   std::unique_ptr<A> hello = std::make_unique<A>();
   std::cout << hello->a << std::endl;
}

In the above code, I mentioned default constructor, I got output for hello->a as a garbage value(random negative value)

But, when I change the struct as below,

struct A {
  int a, b;
  A() {a=0;b=0;}
  A(int w, int e) : a(w), b(e) {}
};

The result value of hello->a as 0.

Why default constructor not assign the int as 0 when using std::make_unique()?

1

1 Answers

2
votes

The arguments passed to std::make_unique<A>() are the arguments passed to the corresponding constructor of A. Here you're not providing any, hence the default constructor of A will be called.

Why default constructor not assign the int as 0 when using std::make_unique()?

Members of builtin type that are not initialized are left with an indeterminate value. This behavior is not related to either std::unique_ptr or std::make_unique; it is just how builtin types are default initialized.

Initialize them:

struct A {
  int a, b;
  A(): a(0), b(0) {}
  A(int w, int e) : a(w), b(e) {}
};