The author must be respected:
Copyright Notice: This article by (TA) original, reprint please keep the article source.
This article link:http://www.zaojiahua.com/memory-management.html
Today looked at the memory management mechanism of COCOS2DX, some places not too good to understand a very long time, now feel their understanding of the almost, and quickly write their own ideas and the vast number of friends to share the Internet, if you find the wrong place or do not understand where to welcome corrections. First we have to talk about the allocation of the memory space of variables in C + +, we write a class in C + +, you can allocate memory space on the stack can also use new on the heap allocation of memory space, if the class object is allocated on the stack of memory space, this memory space management is not our business, But if it is allocated on the heap of memory space, of course, we need to manually delete. COCOS2DX used to allocate memory space on the heap, think of the time you are writing the program for the COCOS2DX in the class is not the most of the factory method to obtain a pointer, you have seen on the stack allocating memory space. So the problem is, since allocating memory space on the heap, how to manage this memory space and when it should be released is a problem. In the program, when we create an object, this memory space is often referenced by different objects, if deleted early, the object is still referencing the memory space, then the program must crash. So COCOS2DX introduces the memory management mechanism of reference counting.
When we allocate a piece of memory space on the heap, the reference count of this object is 1, when there is an object to reference this memory space, the reference count is increased by 1, when the object no longer references this memory, the reference count is reduced by 1, When the reference count is reduced to 0, use Delete to remove this memory, so that when there is an object reference will be normal access to this block of memory, the reference can be normal recovery. Let's take a look at the following code, and the problem with reference counting will be clear.
| 1 |
When an object is created, the reference count is set to 1, which is done in its constructor, and it first invokes the constructor of the parent class Ccojbect |
| 2 |
The Ccobject constructor is shown below |
| 3 |
Ccobject::ccobject (void) |
| 4 |
, M_ureference (1) {}//When the ' object is created ', the reference count of it is 1 |
| 5 |
Ccsprite * Sprite = new Ccsprite (); |