We know that in c, alloc/free is a pair, and in c++, new/delete is a pair, but it operates on pointers. Question: How to release the object?
For example:
A* a=new A();
delete a;
The above is to release the pointer.
----
If B b, then how can I release b? Can't delete it? ? ? Solving! ! !
------------
Answer: Objects can be stored in heap or stack, and release is only valid for objects stored in heap. Objects stored in stack, no release is needed.
To operate objects in heap, there are two ways in C++, by reference or pointer. So when you want to release some objects,
It must be done by malloc/delete pointer
------------
Answer: Objects can be stored in heap or stack, and release is only valid for objects stored in heap. Objects stored in stack, no release is needed.
To operate objects in heap, there are two ways in C++, by reference or pointer. So when you want to release some objects,
It must be done by malloc/delete pointer
Class A
{
...
};
Class B
{
...
};
.
.
.
A* a = new A();//The pointer from new is placed in the heap and needs to be deleted manually; (The same is true for malloc and free)
B b;//Object b is stored in the stack. After leaving the survival cycle, the system will automatically release the memory space it occupies.
------------ So what is heap and what is stack?Stack, when executing a function, the storage units of local variables in the function can be created on the stack, and these storage units are automatically released when the function is executed. The stack memory allocation operation is built into the processor's instruction set and is very efficient, but the allocated memory capacity is limited.
Heaps are those memory blocks allocated by new. The compiler does not care about their release and is controlled by our application. Generally, a new corresponds to a delete. If the programmer does not release it, the operating system will automatically recycle it after the program is finished.
----------------
I have used IOS too much, and I was thinking, if I want to return an object in the function, I new A in the function body, where should I delete it? C++ does not have counters like ObjC. . . Alas, I have forgotten all the foundation of c/c++. Check the information. .
If the function body wants to put back an object,
Reference: /zhanghefu/article/details/5003407
/topics/390314416