aGrUM 2.3.2
a C++ library for (probabilistic) graphical models
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:

Classes

class  gum::RefPtr< Val >
 Smart pointers. More...

Functions

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

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;

Function Documentation

◆ swap()

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 269 of file refPtr_tpl.h.

269 {
270 // save from's content
271 Val* tmp_val = ptr2._val_;
272 unsigned int* tmp_refcount = ptr2._refcount_;
273 // modify from's content
274 ptr2._refcount_ = ptr1._refcount_;
275 ptr2._val_ = ptr1._val_;
276 // modify this's content
277 ptr1._val_ = tmp_val;
278 ptr1._refcount_ = tmp_refcount;
279 }
unsigned int * _refcount_
A reference counter on *val.
Definition refPtr.h:361
Val * _val_
The dumb pointer encapsulated into the "smart" pointer.
Definition refPtr.h:358