为什么我在使用 unique_ptr 时没有调用析构函数?

Why don't I get destructors called when using unique_ptr?

这里我正在创建动态分配的 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);