Smart Pointer

ProudNet includes Smart Pointer class.

Smart Pointer is a functionality that guarantees the existence of object as long as its variables that refer to the created objects exist. And if they cease to exist, then the object simply gets destroyed. Smart Pointer also solves the issues of referring to already destroyed objects (dangling) due to a bug made by developer or not destroying the objects (leak) at all.

The object reference counter of Smart Pointer increases by one at each copy of variable. In the below diagram, Object Instance exists until there is no more Smart Pointer variable or the reference counter becomes 0.

smart_ptr.jpg
Relationship between Smart Pointer and Object

ProudNet's Smart Pointer is Proud.RefCount.

Here is the practical usage of Smart Pointer.

class A {...};
void Foo()
{
// A object is created.
// variable b shares with variable a. A's counter becomes 2.
// release variable a. But it doesn't get destroyed since the counter is still 1.
// release variable b. There is no variable referring A, thus A gets destroyed (delete gets called.)
}

There would cases where you simply want to destroy object when there are Smart Pointers that refer to object in several locations. For instance, if you have an object containing open file handle and Smart Pointer is referring to it, then you may want to destroy that object. But if Smart Pointers here and there are referring to the object, you could run into a trouble since you don't explicitly know when the object needs to be destroyed.

In the case like this, you can do Dispose Pattern. Through Dispose Pattern, you can explicitly destroy the object being referred by several Smart Pointers.