In unmanaged C++, how do I clear objects from memory?
-
1It depends on how you create them.Yakov Galka– Yakov Galka2011-03-22 10:17:15 +00:00Commented 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!Bo Persson– Bo Persson2011-03-22 10:38:30 +00:00Commented Mar 22, 2011 at 10:38
-
4BTW, it is not "unmanaged C++", it is native C++.Bo Persson– Bo Persson2011-03-22 10:42:17 +00:00Commented Mar 22, 2011 at 10:42
Add a comment
|
4 Answers
That depends how you allocated them:
newshould be matched bydeletenew[]should be matched bydelete[]mallocshould be matched byfree(you should never have to use this in C++ though)
Now, forget all these things, use Smart Pointers and read about RAII.
6 Comments
Prasoon Saurav
Using
malloc in C++ (consider user defined types) is a bad idea.Björn Pollex
@Prasoon: Way ahead of you :)
InfoLearner
WITH NULL: error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) 940
Björn Pollex
@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.
Damon
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.
|
You can only delete those which you allocate with new, otherwise an exception will be thrown.
2 Comments
Nocturnal
delete Object; delete [] Array;
Mike Seymour
You almost certainly won't get an exception; it's undefined behaviour.