COOLFluiD  Release kernel
COOLFluiD is a Collaborative Simulation Environment (CSE) focused on complex MultiPhysics simulations.
Shared pointers and Handles

boost::shared_ptr<T>

A boost::shared_ptr is a specialized pointer to the allocated object that keeps and shares ownership with other boost::shared_ptr's to the same object. The allocated object is deleted from memory only when all boost::shared_ptr's are deleted.

Following snippet shows the advantages of boost::shared_ptr, used for the Component environment

// Allocate a component and store it in a boost::shared_ptr "ptr1"
boost::shared_ptr<ComponentType> ptr1 = common::allocate_component<ComponentType>("component_name");
// Share ownership of the component with another boost::shared_ptr "ptr2"
boost::shared_ptr<ComponentType> ptr2 = ptr1;
// Reset ptr1, telling the boost::shared_ptr that it no longer shares ownership to the component.
ptr1.reset(); // ptr1 gets deleted
// ptr2 still has ownership of the component
std::cout << ptr2->name() << std::endl; // print the name of the component

More information on boost::shared_ptr can be found at boost::shared_ptr docs.

Handle<T>

The Handle class is a specialized pointer type, working together with boost::shared_ptr's. Handle's don't share ownership as boost::shared_ptr's do. Handle's have a mechanism to keep track if there are still boost::shared_ptr's sharing ownership. If all boost::shared_ptr's are deleted, the boost::weak_ptr will know this.

A Handle can be created from any boost::shared_ptr or other handles:

// Create a boost::shared_ptr
boost::shared_ptr<ComponentType> component_shared_ptr = common::allocate_component<ComponentType>("component_name");
// Create a handle from the boost::shared_ptr
Handle<ComponentType> component_handle ( component_shared_ptr );
// Create another handle using the first handle
Handle<ComponentType> another_handle = component_handle;
// Check if handles are valid
is_not_null(component_handle) // returns true
is_not_null(another_handle) // returns true
// Delete the allocated_component
component_shared_ptr.reset()
is_not_null(component_handle) // returns false
is_not_null(another_handle) // returns false

When working with components it is generally advised to use Handles and not boost::shared_ptr's, as algorithms might keep objects in memory, even though the user specifically meant to delete a component from memory.

Common mistake

Do not use Handle as the return type for functions returning a boost::shared_ptr! This shared_ptr will be deleted immediately, and thus delete the allocated object, without transferring ownership to the handle. This mistake will not be caught by compilers!

Send comments to:
COOLFluiD Web Admin