aGrUM  0.13.2
Smart Pointers

RefPtr are a replacement for the usual pointers: they keep track of the number of "smart" pointers pointing to a given element. More...

+ Collaboration diagram for Smart Pointers:

Detailed Description

RefPtr are a replacement for the usual pointers: they keep track of the number of "smart" pointers pointing to a given element.

When an element is no more referenced by any smart pointer, it is deleted. Hence using RefPtr, developers do not have to worry anymore about memory leaks. The correct way to use RefPtr is by creating unnamed temporaries like:

RefPtr ( new
myObject )

In any case, if you decide to pass a named pointer as argument to a RefPtr, make sure you will do it only once, that it is allocated on the heap and that you never try to deallocate it yourself, else your program will crash.

Usage example:
// creation of smart pointer
RefPtr<int> ptr1 (new int (4));
// copying (and sharing) this pointer into new smart pointers
RefPtr<int> ptr2 = ptr1, ptr3;
ptr3 = ptr1;
// make ptr2 point toward nothing (this does not deallocate int (4) as it is
// pointed to by ptr1 and ptr3)
ptr2.clear ();
// modifying the value pointed to by the dumb pointer contained in ptr1
*ptr1 = 5;
// print the content of ptr3
cerr << *ptr3 << " = 5" << endl;
// check whether ptr1 and ptr3 reference the same dumb pointer
if (ptr1 == ptr2) cerr << "reference the same dumb pointer" << endl;
// check whether ptr1 and ptr2 contain a dumb pointer
if (ptr1 && !ptr2) cerr << "check containers" << endl;

Classes

class  gum::RefPtr< Val >
 Smart pointersaGrUM's smart pointers keep track of the number of times the value they point to is referenced. More...
 

Functions

template<typename Val >
void gum::swap (RefPtr< Val > &ptr1, RefPtr< Val > &ptr2)
 Swap the contents of two RefPtr. More...
 

Function Documentation

template<typename Val >
void gum::swap ( RefPtr< Val > &  ptr1,
RefPtr< Val > &  ptr2 
)

Swap the contents of two RefPtr.

The swap function must access to gum::RefPtr private parts.

Definition at line 257 of file refPtr_tpl.h.

References gum::RefPtr< Val >::__refcount, and gum::RefPtr< Val >::__val.

257  {
258  // save from's content
259  Val* tmp_val = ptr2.__val;
260  unsigned int* tmp_refcount = ptr2.__refcount;
261  // modify from's content
262  ptr2.__refcount = ptr1.__refcount;
263  ptr2.__val = ptr1.__val;
264  // modify this's content
265  ptr1.__val = tmp_val;
266  ptr1.__refcount = tmp_refcount;
267  }