在这里,我正在创建动态分配的S对象数组,我希望它们被unique_ptr销毁,这不会发生,并且会出现此错误
命令被信号11终止
这意味着该程序访问了就我而言本不应该访问的内存。
#include <iostream>
#include <memory>
class S{
public:
S(){std::cout<<"Constructor\n";}
~S(){std::cout<<"Destructor\n";}
};
int main() {
S* arr=new S[4];
{
using namespace std;
unique_ptr<S> ptr=unique_ptr<S>(arr);
}
}
new s[4]
如果你使用new[]
的分配必须使用去破坏它delete[]
,不是delete
。
auto ptr = unique_ptr<S[]>(arr);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句