dimanche 30 décembre 2018

What happens when std::make_unique

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()?

Aucun commentaire:

Enregistrer un commentaire