CloudBuilder C++ SDK  v3.0.0
Making social games is easy !
Public Member Functions | Static Public Member Functions | Public Attributes | List of all members
CotCHelpers::CRefClass Struct Reference

#include <CotCHelpers.h>

Inheritance diagram for CotCHelpers::CRefClass:
CloudBuilder::CEventListener CloudBuilder::CMatchEventListener CotCHelpers::CThread CloudBuilder::CMatch

Public Member Functions

void Retain ()
 
void Release ()
 
 CRefClass (const CRefClass &other)
 
CRefClassoperator= (const CRefClass &other)
 

Static Public Member Functions

template<class T >
static T * Retain (T *t)
 
template<class T >
static T * Release (T *t)
 

Public Attributes

unsigned __ref_count
 

Detailed Description

Base class indicating a reference-counted object. The rules are as follow:

Once all the owners have called Release() (the original one which created it as well as all those which called Retain()) the object can be destroyed.

Technically, the object starts with a reference count of 1, calling Release() decrements the count, calling Retain() increments it. When reaching zero, the object is destroyed.

Example:

class C: public CRefClass {
A *member;
C(A *a) {
member = a;
member->Retain(); // Take ownership
}
~C() {
member->Release();
}
A *getMember() {
return member; // Getter so no need to make the caller owner
}
void setMember(A *newMember) {
member->Release(); // Release the original member
member = newMember; // Assign the new one
member->Retain(); // And take ownership on the new one
}
};
C *c = new C(...);
A *a = c.getMember();
c->Release(); // Release what we created, not 'a' which we don't own

Note: you may also create CRefClass'es on the stack. In that case, the original creator shall not call Release() (other objects which have called Retain() may though, as they don't know how the variable was created). The following will work as expected:

void func(C *pointer) {
// This function is unaware of how the object was created so it can Retain/Release it...
pointer->Retain();
...
pointer->Release();
}
C var;
func(&var);
// No need to call var.Release() as it was created on the stack

An exception saying "Freeing an object that is still retained elsewhere" can be triggered if you delete an object without using Release(). This can also happen implicitly when using the stack, as in the following example:

struct A: public CRefClass { ... };
struct B {
A *member;
~B() { member->Release(); }
void setMember(A *newMember) {
member = newMember, member->Retain();
}
void useMember() {
member->doMethod();
}
};
B b;
{
A a;
b.setMember(&a);
}
b.useMember(); // exception

In this example, the object A is destroyed by the compiler as we reach the end of the block, but it is still retained in B. This is why it is highly recommended not to create CRefClass'es on the stack except for local use.


The documentation for this struct was generated from the following file: