eLynx SDK v3.3.0
C++ image processing API reference

Best practices using boost smart pointers

Here are summarized the main rules for using boost smart pointer.

Read Boost documentation on Smart pointers.
It has everything you need to know about them and you don't need to read anything else.


Definitions

There are four main types of smart pointer:

The main difference between the scoped and shared pointers is the moment when the resource is deleted:


Practices

An empty smart pointer does not own any resource

boost::shared_ptr<int> sp;

You can re-point it by using reset() method later.

scoped pointer

with C++ classic style:

{                       
  int * pnValue = new int(34);
  ...      
  delete pnValue; pnValue=NULL;
}                       

with boost smart pointer:

{
  boost::scoped_ptr<int> spValue = new int(34);
  ...
} // no need for explicit delete.

shared pointer

with C++ classic style:

int * foo() { return new int[20]; }
 
int main()                        
{                                 
  int * plArray = foo();
  ...
  delete[] plArray; plArray=NULL;
}                                 

with boost smart pointer:

boost::shared_array<int> foo() { return boost::shared_array<int> (new int[20]); }

int main()
{
  boost::shared_array<int> array = foo();
  ...
} // no need for explicit delete.

Accessing pointer from smart pointer

To access to pointer's resource call get() method.

void foo(int * iprValue)
{
  // do something with iprValue, but not delete
}

{ 
  boost::shared_ptr<int> spValue( new int(0) );
  foo( spValue.get());
}

Dereferencing

Same as for a raw pointer:

class A { void foo() {}; };
 
boost::scoped_ptr<A> spA( new A() );
  
// Calling foo method
spA->foo();
 
// Dereferencing
A a = *spA;

Type conversions

If you have a hierarchy of classes

class Derived : public Base {}; 

then you can use boost_shared_prt<Base> to hold a pointer Derived:

boost::shared_prt<Base> spBase( new Derived );

To do the other way around you need boost type cast functions:

boost::shared_ptr<Base> foo() { return boost::shared_ptr<Derived>( new Derived ); }

boost::shared_ptr<Derived> spDerived = boost::static_pointer_cast<Derived, Base>( foo() );

Using regular static_cast won't work since you will have two independent shared pointers trying to manage the same resource.

// Don't do this
boost::shared_ptr<Derived> spDerived = static_cast< boost::shared_ptr<Derived> > (foo());

Illegal code

Since smart pointer owns the resource the following code is illegal:

// Don't do this
int * pn = new int(1);
boost::shared_ptr sp1(pn);
boost::shared_ptr sp2(pn);

sp1 and sp2 know nothing about each other and will try to delete resource pn multiple times.

// The right code
boost::shared_ptr sp1( new int(1) );
boost::shared_ptr sp2 = sp1;




Generated on Thu Dec 9 2010 by doxygen 1.7.2