Reputation: 15598
In unmanaged C++, how do I clear objects from memory?
Upvotes: 2
Views: 281
Reputation: 981
{
Object obj = Object;
// no need to delete this one it will be delete when it gos out of scop
}
Object* obj;
{
obj = new Object();
// you need to delete this one because you used the "new" keyword, even if it gos out of scop
}
delete obj;
Upvotes: 0
Reputation: 76778
That depends how you allocated them:
new
should be matched by delete
new[]
should be matched by delete[]
malloc
should be matched by free
(you should never have to use this in C++ though)Now, forget all these things, use Smart Pointers and read about RAII.
Upvotes: 13
Reputation: 683
You can only delete those which you allocate with new, otherwise an exception will be thrown.
Upvotes: 0
Reputation: 92854
You need not worry about variables allocated on stack. If memory is allocated on the heap using new
you need to use delete
MyClass *p = new MyClass();
// Code
delete p;
Upvotes: 1