Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何对阵列使用唯一的_ptr_C++_Unique Ptr_Move Constructor - Fatal编程技术网

C++ 如何对阵列使用唯一的_ptr

C++ 如何对阵列使用唯一的_ptr,c++,unique-ptr,move-constructor,C++,Unique Ptr,Move Constructor,我有一节课 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 } A类{ 公众: A

我有一节课

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
}
A类{
公众:

A(){cout要对数组分配使用
unique_ptr
,您需要使用它的专门化:

unique_ptr<A[]> a(new A[5]);
unique_ptr a(新的a[5]);

我知道,但我只是想知道,当我从类A中删除析构函数时,这段代码为什么会起作用。它不会起作用,因为并不是所有的析构函数都会被调用。我刚刚用注释过的析构函数尝试了这段代码,它显示为“CCCCC”我关于不工作的评论不是关于构造函数,而是关于
unique\u ptr
超出范围时的析构函数。因为使用
delete
删除分配了
new[]
的对象(而不是
delete[]
)导致未定义的行为。除此之外,这对您来说并不重要。您了解
A
A[]
之间的区别吗?请不要写“不工作”,这是没用的。它可能无法编译(什么错误消息?)或者正在崩溃(根据调试器在哪里?)或者它产生了一个意想不到的结果(哪一个,预期的是什么?),等等。问题的标题很可怕。
unique_ptr<A[]> a(new A[5]);