aGrUM  0.20.3
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:

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

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

References gum::Set< Key, Alloc >::emplace().

251  {
252  // save from's content
253  Val* tmp_val = ptr2._val_;
254  unsigned int* tmp_refcount = ptr2._refcount_;
255  // modify from's content
256  ptr2._refcount_ = ptr1._refcount_;
257  ptr2._val_ = ptr1._val_;
258  // modify this's content
259  ptr1._val_ = tmp_val;
260  ptr1._refcount_ = tmp_refcount;
261  }
+ Here is the call graph for this function: