Smart pointer in COCOS2D-X

Source: Internet
Author: User

Smart pointer in COCOS2D-X
The basis for all memory management methods in the Cocos2d-x is the reference count. After a Ref object is dynamically allocated, its reference count is 1 and its reference count is increased and reduced through retain and release. Reference counting itself does not help us with memory management.


In order to release the object's memory correctly, the Cocos2d-x uses the automatic recycle pool mechanism in Objective-C to manage the release of the object's memory. Autorelease is a bit similar to a shared "smart pointer". The "smart pointer" has the scope of a frame. After the frame ends, it will release its own reference count. At this time, if the object is not referenced by another "share Pointer", the object is released. If the object is referenced, it is retained.


Vector and Map Usually used to work with autorelease. We usually need to add an autorelease object to a Vector or Map. For example, Node stores all the child elements in a Vector. . Vector and Map execute the retain operation on the newly added elements and the release operation on the removed elements. In this way, the elements are automatically released when they are removed from the Vector or Map.


For a single non-set element object, we often do not use autorelease for management, unless it is a temporary object. In this case, we can only manually use retain and release for management, which is equivalent to memory management through new and delete. This can easily lead to memory management problems.


Therefore, the Cocos2d-x introduced the intelligent pointer RefPtr in 3.1, which Is implemented based on RAII [Reference 6], and RAII Is called Resource Acquisition Is Initialization, it is a method for managing dynamic memory proposed by Bjarne Stroustrup, father of C ++. In RAII, the holding of Dynamic resources occurs within the lifecycle of an object, that is, allocating memory in the object constructor and releasing memory in the object's destructor. This is what we described earlier. We will map the dynamically allocated memory to an automatic variable and allocate and release the memory through the constructor and destructor of the automatic variable. This ensures that resources are always released and can be released normally even if exceptions occur. This is also the basic principle of implementation of various SMART pointers, such as std: shared_ptr.


RefPtr is actually implemented by imitating std: shared_ptr in C ++ 11, which maintains a strong reference of a Ref * object, and use the reference count of the Cocos2d-x itself to manage the Memory Sharing of multiple smart pointers. Compared with shared_ptr, it is more lightweight and can be combined with the memory management model of the Cocos2d-x, but it does not guarantee thread safety, so it is more efficient than shared_ptr. However, the Cocos2d-x does not provide smart pointers similar to std: unique_ptr and std: weak_ptr.


3.2.6.1 Constructor


RefPtr needs to rely on Ref's reference count to manage memory, all types of T must be a Ref type, and the Cocos2d-x performs type checks during compilation by statically converting static_const.


RefPtr provides several overloaded constructors. Because the RefPtr variable and the Ref pointer are strongly referenced, these constructors increase their reference count for any Ref pointer that is not nullptr, unless it is a right value. For example:


// Conversion Function
RefPtr <__string> ref2 (cocos2d: String: create ("Hello "));
CC_ASSERT (strcmp ("Hello", ref2-> getCString () = 0 );
CC_ASSERT (2 = ref2-> getReferenceCount ());


// Copy the constructor
RefPtr <__ String> ref4 (ref2 );
CC_ASSERT (strcmp ("Hello", ref4-> getCString () = 0 );
CC_ASSERT (3 = ref2-> getReferenceCount ());
CC_ASSERT (3 = ref4-> getReferenceCount ());


In C ++, only one constructor can be considered as a conversion function. In the above example, The Conversion Function of type T * executes + 1 on the reference count of T, the copy constructor used for ref2 with the left value also executes the reference count + 1 for the referenced memory. By copying constructor and Conversion Function, multiple RefPtr objects can share one Ref object, and each of them maintains a strong reference relationship to Ref.


The copy constructor of the right value does not increase the reference count. Because the method that returns the right value is usually not responsible for managing the memory of the object, at this time, the recipient should not be the sharing party, but should be transferred to the memory usage, for example:


RefPtr <__ String> getRefPtr ()
{
RefPtr <__string> ref2 (cocos2d: String: create ("Hello "));
CC_ASSERT (strcmp ("Hello", ref2-> getCString () = 0 );
CC_ASSERT (2 = ref2-> getReferenceCount ());


Return ref2;
}


// Mobile replication Constructor
RefPtr <__ String> ref4 (getRefPtr ());
CC_ASSERT (strcmp ("Hello", ref4-> getCString () = 0 );
CC_ASSERT (2 = ref4-> getReferenceCount ());


The getRefPtr () method returns a right-value RefPtr <__string> smart pointer. The mobile replication constructor is called and the management of the memory of the returned object is transferred rather than shared, it does not increase the reference count of the right value.


In addition, we can use three special methods to construct an empty smart pointer:


// Default constructor
RefPtr ref1;
CC_ASSERT (nullptr = ref1.get ());


// Construct with NULL pointer Parameters
RefPtr <__ String> ref3 (nullptr );
CC_ASSERT (_ String *) nullptr = ref3.get ());


// Use the smart pointer copy construction with null reference
RefPtr ref5 (ref1 );
CC_ASSERT (Ref *) nullptr = ref5.get ());


3.2.6.2 value assignment operator


Similar to the constructor, RefPtr should share resources with the left value and increase its reference count. For the right value, it should still use transfer instead of share. Unlike constructors, the value assignment operator not only increases the reference count of its resources, but also releases the reference count of the old resources.


Previously, RefPtr defined a conversion function for type T *. In C ++, the conversion function is used to execute forced conversion or value assignment. For example:


RefPtr <__string> ptr = cocos2d: String: create ("Hello ");


In fact, the conversion constructor from T * To RefPtr will be called, but this is not what we want, because the ptr variable may be holding other resources. Therefore, RefPtr provides an overload of the T * value assignment operator:


Template class RefPtr
{
Public:
Inline RefPtr & operator = (T * other)
{
If (other! = _ Ptr)
{
CC_REF_PTR_SAFE_RETAIN (other );
CC_REF_PTR_SAFE_RELEASE (_ ptr );
_ Ptr = const_cast: type *> (other );
}


Return * this;
}
};


The conversion method is not directly called when T * is converted, so that the old resources can be released. In addition, nullptr can be used to make RefPtr a null smart pointer.


3.2.6.3 weak Reference Assignment


Whether it is a copy constructor or a value assignment operator, RefPtr maintains a strongly referenced relationship with any non-null left value resource. Sometimes we may still want to maintain a weak reference relationship for resources with the left value, for example:


RefPtr image;
Image = new cocos2d: Image ();
Image-> release ();


If the image object with the left value can be constructed based on weak references, the syntax is greatly simplified and error-prone. RefPtr provides a weakAssign method to implement weak references:


Template class RefPtr
{
Public:
Inline void weakAssign (const RefPtr & other)
{
CC_REF_PTR_SAFE_RELEASE (_ ptr );
_ Ptr = other. _ ptr;
}
};


Therefore, the preceding example can be converted into the following concise and error-prone statement:


RefPtr image;
Image. weakAssign (new cocos2d: Image ());


Careful friends will immediately find that using new Image () as a parameter will lead to the call of the conversion function, and the conversion function will increase its reference count, then the new Image () the reference count will still be added. However, the actual execution process can be converted to the following statement:


RefPtr image;
RefPtr temp (new Image (); // The conversion constructor. The reference count is 2.
Image. weakAssign (temp); // The reference count is 2.


Temp is an automatic variable within the scope of the weakAssign method. After the weakAssign method is executed, the temp temporary variable will be destroyed to execute the Destructor and release its resource occupation, change the reference count to 1.


3.2.6.4 other operations


Other operations of RefPtr include releasing resources in the destructor, which follows the RAII principle to release resources at the end of the object lifecycle. You can also call the reset method to release the resource occupation and change it to a null smart pointer.


In addition, RefPtr reloads the * operator so that it can directly access the resource address. In addition, you can also use the get method to access the resource address.


For smart pointers, common methods also include determining the resource validity. We can compare the results obtained by the get method with the nullptr to determine the validity of the smart pointer, in addition, RefPtr also reloads the bool () operator so that we can directly determine its validity. For example:


RefPtr <__ String> ref1 = _ String: create ("Hello ");
CC_ASSERT (true = (bool) ref1 );


Ref1 = nullptr;
CC_ASSERT (false = (bool) ref1 );


RedPtr also contains some reloads on comparison operators and type conversion. We will not detail them here. You can view the source code on your own.


3.2.6.5 RefPtr and container


If you want to add an element to a container, you also need to use the container to manage the memory usage. The answer is yes if RefPtr can be directly added to the Vector and Map containers.


As we have mentioned earlier, RefPtr provides a conversion constructor to convert a T * To RefPtr. In fact, RefPtr also provides a conversion operator to T:


Inline operator T * () const {return reinterpret_cast (_ Ptr );}


The pushBack method of the Vector receives a T pointer, so that the operator T * will be automatically called and added to the Vector. The memory of the elements added to the Vector will also be shared and managed by the Vector, the following code:


Auto str = new _ String ("Hello ");
RefPtr <__ String> ref1 = str;


Vector <__ String *> v;
V. pushBack (ref1 );


In this way, RefPtr can be combined with containers in the Cocos2d-x to manage memory, making the management of memory more flexible. Of course, you can also directly use the * operator or get method to directly obtain the resource address and pass it to the Vector, which simplifies the operation.


3.2.6.6 comparison between RefPtr and automatic recycle pool


So far, the Cocos2d-x provides two ways to choose to manage the release of memory: autorelease and RefPtr, so how do we choose to use these two memory management methods?


To compare their advantages and uses, we try to replace each other with each other. First, we use autorelease to replace RefPtr. Because it is completely dependent on the release of the automatic recycle pool, the shared variables have almost no control over resource usage.


If you use RefPtr to replace autorelease, any reference to Node resources is strongly referenced, so that when a Node is removed from the UI tree, we also need to use the reset to release its occupation of Node resources, which is obviously uncontrollable.


Therefore, for UI elements, we completely need to use a weak reference type of memory management. Only the UI tree itself can allocate and release memory, and other places can only be weak references. Although RefPtr provides a weak Reference Assignment, RefPtr cannot cooperate well with Vector. Managing UI elements with RefPtr becomes extremely complex.


Therefore, for the two memory management methods, the author suggests that all UI elements must be managed using autorelease, while the data in the game uses the smart pointer RefPtr.


3.2.6.7 RefPtr Defects


Intelligent pointers in Cocos2d-x also have some defects, which are not obvious, but developers who are not familiar with their mechanisms may also encounter these confusions.


First, the reference count can be externally controlled by RefPtr. For example:


Auto str = new _ String ("Hello ");
RefPtr <__ String> ptr;
Ptr. weakAssign (str );
Str. release ();
(* Ptr)-> getCString (); // access the wild pointer. An error is returned.


Since the reference count can be modified externally, the resource situation in RefPtr may become complicated, and it may have been released, resulting in running errors when its constructor releases it, developers need to be cautious about the combination of manual memory management and smart pointers. This situation does not exist in std: shared_pre, because the developer cannot modify the reference count externally.


Secondly, although RefPtr provides a weak reference, the weak reference smart pointer still acts as a strong smart pointer and can still modify its resources, as a result, the behavior of the original smart pointer becomes unpredictable. For example:


RefPtr <__ String> ptr1 (new _ String ("Hello"); // reference count 2
RefPtr <__ String> ptr2;
Ptr2.weakAssign (ptr1); // reference count 2
Ptr2.reset (); // reference count 1
Ptr2.reset (); // released
(* Ptr1)-> getCString (); // Error


In C ++ 11, the weak referenced std: weak_ptr is restricted to accessing the original std: shared_ptr variable only through its lock member, so as to operate on the resource memory. This ensures the effectiveness of smart pointers. In Cocos2d-x, we need to be careful to ensure the legitimacy of the smart pointer. This is confusing for developers to some extent.




Your personal blog www.sundabke.com will be released first.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.