-1

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.

6
  • 4
    What garbage collection?
    – Blindy
    Commented May 5, 2021 at 19:58
  • 2
    Standard c++ has no garbage collection. Remember the c++ tag is for standard / unmanaged c++ not .net / clr. If you are using .NET you may want to remove c++ and add c++-cli
    – drescherjm
    Commented May 5, 2021 at 20:00
  • 4
    Never use new, and you won't need to use delete. Instead use containers like std::vector and smart pointers like std::unique_ptr.
    – Eljay
    Commented May 5, 2021 at 20:01
  • 2
    Simplified rule: What you new, you must delete. What you new[], you must delete[]. It's a lot of work, so start by using the containers in the standard library instead.
    – Ted Lyngmo
    Commented May 5, 2021 at 20:01
  • 7
    Modern 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.
    – drescherjm
    Commented May 5, 2021 at 20:03

1 Answer 1

2

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[].

0

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.