2

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

3
  • 1
    It depends on how you create them. Commented Mar 22, 2011 at 10:17
  • If you don't explicitly use new or malloc (or some crazy strdup :), you don't have to. It just works! Commented Mar 22, 2011 at 10:38
  • 4
    BTW, it is not "unmanaged C++", it is native C++. Commented Mar 22, 2011 at 10:42

4 Answers 4

13

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Using malloc in C++ (consider user defined types) is a bad idea.
@Prasoon: Way ahead of you :)
WITH NULL: error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) 940
@KnowledgeSeeker: If you have a specific problem with specific code, post that code (a minimal compilable example that reproduces the error). Do not post that code in a comment. Edit your question, or ask a new question about it.
That C2679 error suggests that you tried to assign null to an object which is not a pointer. This only works with "numberlike" primitive types, and pointers, and with objects that have an explicit operator= for an int type. Note that in any case assigning null to a pointer does not free any memory.
|
1

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;

Comments

0

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

2 Comments

delete Object; delete [] Array;
You almost certainly won't get an exception; it's undefined behaviour.
0
{
    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; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.