Reputation: 71
class finder
{
public:
finder();
~finder();
}
int _tmain(int argc, _TCHAR* argv[])
{
finder* pfind = new finder(L"test");
finder find(L"test2");
system("PAUSE");
return 0;
}
What I know that find's destructor will be called after program exit, but pfind's destructor won't be called. My question is why? And Should I add
delete _pfind;
before return 0?
Upvotes: 0
Views: 3337
Reputation: 956
Mat is right, however I noticed you are using CLR/.Net C++ (or whatever they call it these days). I believe this comes with a gcnew
keyword which will do the same thing as the new
keyword but delete the object at the end of its scope. This is also known as garbage collection. On a personal note having both new
and gcnew
is a great tool because they both fit nicely into diffrent situations. Please keep in mind you code will not be cross-platform if you use gcnew
.
Upvotes: 0
Reputation: 206689
The "why" is because you're responsible for managing the lifetime of objects you create with new
.
The language says that objects with automatic storage duration (like find
in your example) live as long as the block in which they are created. These get automatically deleted (you must not do it yourself) at the appropriate time (i.e. generally when you leave that block.)
Dynamic storage duration objects (like what pfind
points to) last until you delete them. Nothing will delete them for you.
So yes, you need to delete it yourself in this case, with delete pfind;
.
(Or use the appropriate type of smart pointer for your use case.)
Upvotes: 3
Reputation: 239291
Yes, you should explicitly clean up the memory you allocate by calling delete
on your unmanaged pointers. Typically any block of code which allocates memory via new
must be balanced by a block of code which deallocates that memory via delete
.
Upvotes: 1