What does the use of new require you to also call delete?

一曲冷凌霜 提交于 2019-12-11 19:39:13

问题


I am here stuck with a question in my C++ book with the following:

"What does the use of new require you to also call delete?"

Maybe you have an answer for that?


回答1:


Because that is the way C++ is designed & that is the intended behavior.
The intention was to provide a memory allocation which you demand and own till you reliquish it explicitly.

new gives you a dynamic memory allocation(on heap) which will continue to exist and you own it untill you explicitly deallocate it by calling delete.
Failing to call a delete on a newed buffer will lead to Undefined Behaviors usually in the form of. 1 memory leaks.

1 This was discussed here.




回答2:


when you do a new, OS allocates the memory to the pointer you are assigning it. After your usage is completed you may not require it anymore. But the memory is still marked as "being used" by OS.

Now, when the pointer is declared in a scope of a function or any other block (of {}), it will be deleted (only pointer will be removed) when the execution of the block is over. In such cases the memory that was allocated using new is remained marked "being used" by OS and is not allocated to any other pointer that calls new or to a variable. This causes an orphan block of memory in RAM, that will never be used because its pointer was removed from memory but it will occupy a memory block.

This is called a memory leak. A few of such blocks may make your application unstable as well.

You use delete to free such memory blocks and relieve the OS so that it can be used well for other requests




回答3:


There is no Garbage Collector in C++, and therefore you are responsible for deallocating the allocated memory. Anyway, the operating system "knows" what memory your program allocated. So when your program exits, the operating system is again responsible for the memory. But if you have a long running C++ program and never call delete noone will help you to get rid of your garbage.




回答4:


Calling new has allocated memory for the object and it has also arranged for the constructor of that object to be executed.

You could free the memory by calling free(), but you should actually use delete to free memory allocated by new, since this will also cause the objects destructor to be executed.



来源:https://stackoverflow.com/questions/9920238/what-does-the-use-of-new-require-you-to-also-call-delete

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