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

Viewed 137

Here I am creating dynamically allocated array of S objects and I expect them to be destroyed by unique_ptr, which doesn't happen and I get this error

Command terminated by signal 11

and that means the program accessed memory which it shouldn't have accessed as far as I am concerned.

#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);
    }
}
1 Answers
new s[4]

If you use new[] allocation you have to destroy it using delete[], not delete.

    auto ptr = unique_ptr<S[]>(arr);
Related