Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
    }
}
like image 298
Erik Nouroyan Avatar asked Nov 30 '25 08:11

Erik Nouroyan


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);
like image 88
KamilCuk Avatar answered Dec 01 '25 21:12

KamilCuk