简体   繁体   中英

When do I have to free memory?

I learned C# and now I'm learning C++. The whole point of releasing a memory is new for me, and I want to know when I need to worry about memory releasing and when I don't.

From what I understand, the only case I have to worry about the release of memory, is when I used new operator, so I should to release the memory by using delete .
But in these cases there is no need to release the memory:

  • Class variables (Members), or static variables.
  • Local variables in function.
  • STL family (string, list, vector, etc.).

Is this true?
And are there other cases where I have to worry about memory releasing?

You basically got it right: You need to balance new with delete , new[] with delete[] , and malloc with free .

Well-written C++ will contain almost none of those, since you leave the responsibiltiy for dynamic memory and lifetime management to suitable container or manager classes, most notably std::vector and std::unique_ptr .

As a general rule of thumb I tend to abide by the following:

  • If I code a new/new[] i immediately code the corresponding delete/delete[]
  • Likewise any malloc/calloc is immediately followed by the relevant free

This avoids many nasty situations where you can generate a memory leak. If you are new to C++ I would not get used to malloc and its many variants, it requires a lot of scaffolding to remain type-safe, which unless truly necessary can be counted as a bad thing, however, as mentioned, there are times it is necessary: for example, when having to use C-based libraries/APIs then you may conceivably need to use them.

In the main stay well clear of them and your life will be much easier.

Note: I mention the points above, as having gone from C to C++ I have had to face up to a lot of old tried and tested techniques from C which cause problems in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM