Utils

A collection of core utilities used by Lima and camera plugins.

Smart Handle

Resource acquisition is initialization (RAII) is a programming idiom developed for exception-safe resource management. Pointers, mutexes are well covered by the standard library with std::unique_ptr, std::shared_ptr, std::lock_guard, etc… But for opaque handle type we don’t have standard option. This library try to fill this niche.

Usage

Let’s consider the HDF5 File API as an example:

// Returns a file identifier if successful; otherwise returns a negative value.
hid_t H5Fopen( const char *name);
// Returns a non-negative value if successful; otherwise returns a negative value.
herr_t H5Fclose(hid_t file_id);

We would like to close the file in any circumstance as unclosed file is a well-known source of corrupted data.

#include <lima/utils/raii.hpp>

namespace raii = lima::raii;

// Define handle type
using file_handle_t = lima::unique_handle<hid_t, decltype(&::H5Fclose), ::H5Fclose, raii::not_negative>;

file_handle_t file_id(H5Fopen("foo.h5"));

In this example, if file_id gets out of scope, H5Fclose will be called but only if the handle is checked to be valid by the raii::not_negative policy.

If a Copyable handle is required, a shared_handle can be used instead:

using shared_file_handle_t = lima::shared_handle<file_handle_t>;

Note that shared_handle takes a unique_handle as template argument.

Synoptic

template<
    typename  T,                            // A handle type
    typename CloseFunctionType,             // The handle close function type
    CloseFunctionType close,                // The close function pointer
    typename ValidPolicy = not_nullptr      // A policy that specify the validity domain of the handle
>
class unique_handle;

ValidPolicy

struct ValidPolicy
{
    // Returns true if the given handle is valid
	static bool is_valid(T const& h) noexcept;
    // Returns an invalid handle value (used for default initialization)
	static /* unspecified */ invalid_value() noexcept;
};