问题
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 new
ed 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