[ VIGRA Homepage | Function Index | Class Index | Namespaces | File List | Main Page ]

utilities.hxx File Reference |

`#include "config.hxx"`
`#include "error.hxx"`
`#include "metaprogramming.hxx"`
`#include "tuple.hxx"`
`#include "diff2d.hxx"`
`#include "mathutil.hxx"`
`#include <string>`
`#include <sstream>`
`#include <cctype>`
`#include <tuple>`

Go to the source code of this file.

## Namespaces

| vigra

## Macros

#define | VIGRA_FINALLY(destructor) VIGRA_FINALLY_IMPL(destructor, __COUNTER__)

## Functions

template<class T >
std::string | asString (T t)(...)
template<typename TPL , typename FUNCTOR >
void | for_each_in_tuple (TPL &&t, FUNCTOR &&f)
std::string | normalizeString (std::string const &s)
std::string | tolower (std::string s)

## Macro Definition Documentation

## ◆ VIGRA_FINALLY

#define VIGRA_FINALLY | ( |  | destructor | ) | VIGRA_FINALLY_IMPL(destructor, __COUNTER__)

Emulate the 'finally' keyword as known from Python and other languages.

This macro improves upon the famous Resource Acquisition Is Initialization idiom, where a resource (e.g. heap memory or a mutex) is automatically free'ed when program execution leaves the current scope. This is normally achieved by placing a call which releases the resource into the destructor of a dedicated helper class (e.g. `std::unique_ptr` or `std::lock_guard<std::mutex>`).

Traditionally, a separate helper class is needed for every type of resource to be handled. In contrast, the macro `VIGRA_FINALLY` creates such a class on the fly by means of an embedded lambda expression.

Usage:

#include <vigra/utilities.hxx>

std::mutex my_mutex;
...
{
// the following two lines are equivalent to
// std::unique_ptr<std::string> my_string = new std::string("foo");
std::string * my_string = new std::string("foo");
VIGRA_FINALLY(delete my_string);
// the following two lines are equivalent to
// std::lock_guard<std::mutex> lock(my_mutex);
my_mutex.lock();
VIGRA_FINALLY(my_mutex.unlock());
...
}
// the string has been deallocated and the mutex is unlocked

You can pass any code to this macro. Multiple statements must be enclosed in braces as usual. Arbitrary many calls to `VIGRA_FINALLY` can be placed in the same scope. Their actions will be executed in the reversed order of declaration:

int i = 0;
...
{
VIGRA_FINALLY({ // execute multiple statements
i = i*i;
++i;
});
VIGRA_FINALLY( i += 2 ); // this executes first
assert(i == 0); // as yet, nothing happend
}
assert(i == 5); // 'finally' code was executed in reversed order at end-of-scope

This idea was popularized by Marko Tintor in The Auto Macro: A Clean Approach to C++ Error Handling.

VIGRA_FINALLY
#define VIGRA_FINALLY(destructor)
Definition: utilities.hxx:207

© Ullrich Köthe (ullrich.koethe@iwr.uni-heidelberg.de) Heidelberg Collaboratory for Image Processing, University of Heidelberg, Germany | html generated using doxygen and Python vigra 1.11.1