So I know that memory management is important in c++, but usually, garbage collection gets neglected in my c++ programs. I know there are some important cases where you want to use the delete operator so that you don't encounter a memory leak, but I'm not sure what they are.
1 Answer
When you use the new operator, memory is allocated on the heap. In order to free that memory, call delete on it. For example, for an int:
int * p_myint = new int;
delete p_myint;
Or for an object of a user-defined class:
MyClass * p_myobject = new MyClass;
delete p_myobject;
In general, each use of new requires a use of delete.
Note that to allocate memory for an array (and some related types), you use new[], and the allocated memory is similarly freed by delete[]. E.g.:
int * p_myints = new int[3];
delete[] p_myints;
Again, each use of new[] generally requires a use of delete[].
c++has no garbage collection. Remember thec++tag is for standard / unmanagedc++not .net / clr. If you are using .NET you may want to removec++and addc++-clinew, and you won't need to usedelete. Instead use containers likestd::vectorand smart pointers likestd::unique_ptr.new, you mustdelete. What younew[], you mustdelete[]. It's a lot of work, so start by using the containers in the standard library instead.c++encourages you to avoid the use of new. Instead use containers of the standard library and when you can't there are also smart pointers.