Mopping up template barf with static_assert

Templates are a mixed blessing for C++ developers. On the one hand, templates avoid code duplication as most impressively demonstrated by the standard template library. The template mechanism, in contrast to preprocessor macros, is aware of the C++ language and part of it. Compilers can produce helpful error messages – and some compilers even do so.

Some compilers, however, fail in providing clear template compilation error messages. If you make a mistake, you are greeted by a bucket load of irritating notes on what went wrong in detail. Since it is down to you to identify the relevant chunks, this is often referred to as template barf.

Continue reading “Mopping up template barf with static_assert”

Underprivileged unique pointers: retrofitting make_unique

std::shared_ptr<Value> is one of the starlets in C++11’s recently polished standard template library. shared_ptrs work just like normal C-style pointers except that they keep track of how many pointers point to the same object. Once the last shared_ptr pointing to an object goes out of scope, the object pointed at will be deleted. For convenience, the standard library offers the factory function std::make_shared<Value>():

auto value = std::make_shared<Value>("a", "few", "arguments");

std::make_shared<Value>() creates a new object of type Value, where the arguments given to make_shared() are forwarded to the constructor of Value. The newly created object is immediately wrapped in a std::shared_ptr<Value>, which is then returned to the caller.

Continue reading “Underprivileged unique pointers: retrofitting make_unique”

Resource management

Most computer programs rely on resources provided by the operating system or another software. The most common resource is memory, closely followed by files on the local file system. Be it a chunk of memory or a database connection, resources should be dealt with gently; return them once you no longer need them.

Many text books and university courses on C++ familiarize the programmer with low-level functions such as new and delete. These mechanisms are inconvenient and error-prone since you need to make sure that you release the resource no matter which execution path your program takes. Less obvious paths, for example exceptions in the control flow, tend to be forgotten.

Continue reading “Resource management”