Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use unique_ptr for arrays

I have a class

class A {
public:
  A(){cout<<"C";}
  ~A(){cout<<"D";}
};
int main(){
  unique_ptr<A> a(new A[5]); // - doesn't work 
  unique_ptr<A> a(new A[1]); // - doesn't work
  unique_ptr<A> a(new A); // - works
}

Why does this happen?

I guess that the thing is about the move constructor (it cannot be created automatically because of the destructor), but why do we need a move constructor here?

And what's the difference between:

unique_ptr<A> a(new A[1]); // - doesn't work
unique_ptr<A> a(new A); // -works
like image 854
user3102962 Avatar asked Dec 26 '22 06:12

user3102962


1 Answers

To use unique_ptr with an array allocation, you need to use a specialization of it:

unique_ptr<A[]> a(new A[5]);
like image 112
jxh Avatar answered Jan 05 '23 09:01

jxh