Sometimes a reference count after release is funny

193 Views Asked by At

I'm using cocos2dx, and have a question about autorelease. I have a sprite call autorelease method, after that remove its sprite, and then I confirmed a reference count of its sprite, value was 14.(Actually, it's different every time).

Why a reference count after release is funny? Is this really a memory is released?

↓Before release↓

enter image description here

↓After release↓

enter image description here

2

There are 2 best solutions below

0
Yakk - Adam Nevraumont On

In most reference counting systems, when you release a reference on an object you can no longer trust your pointer. In a multi-threaded environment even if the reference count "before" was 10, you cannot know that "after" it is 9 because another thread could be removing (or adding) references at the same time.

When the last reference count is released, the object is usually recycled. Maybe it is freed or deleted, or maybe it is returned to some other resource management system. Sometimes the memory the object used is overwritten with bookkeeping information while it waits to be reused, at other times it is immediately reused before you get to see it again.

Reading or writing from a pointer that you have released your reference count on should not be done.

0
Khang Dinh Hoang On

The memory is truly released!

When you examine deeper in the code, you will find this:

void Ref::release() { // CCRef.cpp
...
    if (_referenceCount == 0)
        delete this; 
...
}

After released, the memory is no longer an Ref object. It can be used to locate for something else, and that memory's datas can be modified. It is not _referenceCount = 14, it may be 0x00ABC0 = 0x0000000E.