dimanche 1 mars 2015

Should I delete things created by the new keyword in main.cpp?


If I understand correctly (which I am not claiming I do), you should delete anything created with the new keyword in your Destructor for a particular class. That prevents memory leaks. Example:



#include "Bar.h"

Bar bar_;

Foo::Foo()
{
bar_= new Bar();
}

Foo::~Foo()
{
delete bar_;
}


But should you delete new things created in main.cpp? Or will they just be automatically deleted by their Destructors when they go out of scope?



#include "Foo.h"

int main()
{
MakeNewFoo();
//Do other stuff and forget foo ever existed
exit(0);
}

void MakeNewFoo(){
Foo foo = new Foo();
}



Aucun commentaire:

Enregistrer un commentaire