When do I have to free memory?

十年热恋 提交于 2021-02-18 20:53:07

问题


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?


回答1:


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 memo­ry and lifetime management to suitable container or manager classes, most notably std::vector and std::unique_ptr.




回答2:


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++.



来源:https://stackoverflow.com/questions/14626318/when-do-i-have-to-free-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!