InfoLearner
InfoLearner

Reputation: 15598

What are the ways to delete objects in C++?

In unmanaged C++, how do I clear objects from memory?

Upvotes: 2

Views: 281

Answers (4)

Mustafa
Mustafa

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

Björn Pollex
Björn Pollex

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

Nocturnal
Nocturnal

Reputation: 683

You can only delete those which you allocate with new, otherwise an exception will be thrown.

Upvotes: 0

Prasoon Saurav
Prasoon Saurav

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

Related Questions