text:
More C++ Idioms/Expression-template

= Expression Template =

Intent

 * To create a domain-specific embedded language (DSEL) in C++
 * To support lazy evaluation of C++ expressions (e.g., mathematical expressions), which can be executed much later in the program from the point of their definition.
 * To pass an expression -- not the result of the expression -- as a parameter to a function.

Motivation
Domain-specific languages (DSLs) is a way of developing programs where the problem to be solved is expressed using notation that is much closer to the domain of the problem rather than the usual notation (loops, conditionals, etc.) provided by procedural languages. Domain-specific embedded languages (DSELs) is a special case of DSLs where the notation is embedded in a host language (e.g., C++). Two prominent examples of DSELs based on C++ are the Boost Spirit Parser Framework and Blitz++ scientific computing library. Spirit provides a notation to write EBNF grammar directly into a C++ program whereas Blitz++ allows a notation to perform mathematical operations on matrices. Obviously, such notation is not provided in C++ natively. The key benefit of using such notation is that the program captures the intention of the programmer quite intuitively making the program much more readable. It reduces the development as well as maintenance costs dramatically.

So, how do these libraries (Spirit and Blitz++) achieve such a leap in the abstraction-level? The answer is -- you guessed it right -- Expression Templates.

The key idea behind expression templates is lazy evaluation of expressions. C++ does not support lazy evaluation of expressions natively. For example, in the code snippet below, the addition expression (x+x+x) is executed before the function foo is called.

Function foo never really knows how the parameter it receives is computed. The addition expression never really exists after its first and only evaluation. This default behavior of C++ is necessary and sufficient for an overwhelmingly large number of real-world programs. However, some programs need the expression later on to evaluate it again and again. For example, tripling every integer in an array.

This is the conventional way of supporting lazy evaluation of mathematical expressions in C/C++. The expression is wrapped in a function and the function is passed around as a parameter. There is overhead of function calls and creation of temporaries in this technique, and quite often, the location of the expression in the source code is quite far from the call site, which adversely affects the readability and maintainability. Expression templates solve the problem by inlining the expression, which eliminates the need for a function pointer and brings together the expression and the call site.

Solution and Sample Code
Expression templates use the Recursive Type Composition idiom. Recursive type composition uses instances of class templates that contain other instances of the same template as member variables. Multiple repetitive instantiation of the same template gives rise to an abstract syntax tree (AST) of types. Recursive type composition has been used to create linear Type lists as well as binary expression trees used in the following example.

An analogy to the Composite design pattern is useful here. The template DExpression can be considered as the abstract base class in the Composite pattern. It captures the commonality in the interface. In expression templates, the common interface is the overloaded function call operator. DBinaryExpression is a real composite as well as an adaptor, which adapts Add's interface to that of DExpression. Constant and Var are two different types of leaf nodes. They also stick to the DExpression's interface. DExpression hides the complexity of DBinaryExpression, Constant and Var behind a unified interface to make them work together. Any binary operator can take place of Add, for example Divide, Multiply etc.

The above example does not show how recursive types are generated at compile-time. Also, expr does not look like a mathematical expression at all, but it is indeed one. The code that follows show how types are recursively composed using repetitive instantiation of the following overloaded + operator.

The above overloaded operator+ does two things - it adds syntactic sugar and enables recursive type composition, bounded by the compiler's limits. It can therefore be used to replace the call to evaluate as follows:

Known Uses

 * Blitz++ Library
 * Boost Spirit Parser Framework
 * Boost Basic Linear Algebra
 * LEESA: Native XML Programming using an Embedded Query and Traversal Language in C++
 * std::valarray as implemented by GNU libstdc++, LLVM libc++, and others.

Related Idioms

 * Recursive Type Composition

title: More C++ Idioms/Expression-template


text: More C++ Idioms/Compile Time Control Structures

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
More C++ Idioms/Type Selection

= Type Selection =

Intent
Select a type at compile-time based on a compile-time boolean value or a predicate.

Motivation
Ability to take decisions based on the information known at compile-time is a powerful meta-programming tool. One of the possible decisions to be made at compile-time is deciding a type i.e., the choice of the type may vary depending upon the result of a predicate.

For example, consider a Queue abstract data-type (ADT) implemented as a class template that holds a static array of Ts and the maximum capacity of the Queue is passed as a template parameter. The Queue class also needs to store the number of elements present in it, starting from zero. A possible optimization for such a queue class could be to use different types to store the size. For instance, when Queue's maximum capacity is less than 256, unsigned char can be used and if the capacity is less than 65,536, unsigned short can be used to store the size. For larger queues, unsigned integer is used. Type selection idiom can be used to implement such compile-time decision making.

Solution and Sample Code
A simple way of implementing the type selection idiom is the IF template. IF template takes three parameters. The first parameter is a compile-time boolean condition. If the boolean condition evaluates to true the 2nd type passed to the IF template is chosen otherwise third. Type selection idiom consists of a primary template and a partial specialization as shown below.

We now use the type selection idiom to implement the Queue size optimization mentioned above.

The Queue class template declares an array or Ts. The type of the size data member depends on the result of two comparisons performed using the IF template. Note that these comparisons are not performed at run-time but at compile-time.

Known Uses

 * Boost.MPL Library
 * std::conditional

Related Idioms

 * Tag Dispatching

title: More C++ Idioms/Type Selection


text:
More C++ Idioms/Temporary Base Class

= Temporary Base Class =

Intent
Reduce the cost of creating temporary objects.

Motivation
Temporary objects are often created during execution of a C++ program. Result of C++ operators (unary, binary, logical, etc.) and return-by-value functions always give rise to temporary objects. For built-in types, the cost of creating temporaries is minimal because compilers often use CPU registers to manipulate them. However, creation of temporary objects can be quite expensive for user-defined classes that allocate memory in the constructor and may require expensive copy operations in the copy-constructor. Temporaries are often wasteful because their lifespan is usually very short and they exist only to be assigned to a named object (lvalue). Even though their lifespan is short, the C++ language rules require the compilers to create and destroy temporaries to maintain correctness of the program. (In reality, RVO and NRVO optimizations are allowed to eliminate some temporaries). The cost of creating and destroying temporaries can adversely affect the performance of programs that use heavy objects.

Consider, for instance, a  class that uses heap memory to store an array of integers. This class uses the usual RAII idiom to manage the resources: allocation in the constructor and de-allocation in the destructor. The copy constructor and the copy-assignment operator take care of maintaining exclusive ownership of the allocated memory.

Using objects of this class in expression such as below have several performance issues.

Temporary  objects are created as a result of every summation and they are destroyed immediately. For every pair of parenthesis in, a temporary object is needed. Creation and destruction of each temporary requires memory allocation and de-allocation, which is quite wasteful.

Temporary Base Class idiom is a way of reducing the overhead of temporaries in arithmetic expression such as the above. However, this idiom has major drawbacks as described towards the end.

Solution and Sample Code
Temporary Base Class idiom (TBCI) does not change the fact that temporary objects are created but it reduces (substantially) the cost of creating them. This is achieved by recognizing the places where temporaries are created and by using a type that is lightweight to create and destroy. Unlike C++11, C++03 does not have a language supported way of distinguishing temporary objects (rvalues) from named objects (lvalues). Const reference is the only way available in C++03 for binding a temporary object to a reference.

In TBCI idiom, each class for heavy objects is represented by two classes. One class, D (for derived), is meant to represent the named objects whereas another class, B (for base), is used to represent temporary objects. Users are expected to use only D class in variable/function declaration because objects of type D behave just like regular objects. For instance, deep copies are performed when copying D objects.

The B class is used for intermediate temporary objects created in arithmetic expressions. Creation and destruction of B type objects is transparent to the user provided all the results computed by D objects are assigned to another D object. The key difference between B and D classes is the copying behavior. Whenever a B or D object is created from a D object, a deep copy (i.e., new memory allocation and copying data) is performed. On the other hand, whenever a B or D object is created from a B object, a shallow copy (i.e., just copy pointers) is performed. These rules are also applicable to the assignment operators with an exception that existing memory may have to be deleted in the left hand side object (e.g, an assignment from a B to B or D). Moreover, unlike D objects, B objects do not have exclusive ownership of the data and therefore do not destroy it when a destructor is called.

Interfaces of B and D classes are designed carefully to fully support conversion from one another with respect to the rules of memory management given above. The following example is a TBCI version of the  class shown above. The  class is the main class whereas   class is meant to represent temporary matrices.

The interfaces of the above two classes reveal several things. Not only the classes have doubled, number of member function have also (nearly) doubled. In particular, copy-constructor, copy-assignment operator, overloaded  are declared for both   and. This is necessary to ensure that in all possible cases where  and   object come together, the behavior is well-defined.

The only way  objects are created are through the overloaded   in the   class. Whenever two  classes are added, the result is returned as a   object. The result of any subsequent additions of  objects are stored in the same   object that is a result of the first addition. This eliminates the need to allocate and de-allocate memory for temporary matrices. For instance, TBCI achieves efficiency by executing addition of 4 matrices in the following way.

New memory is allocated only when the  object is created the first time. The results of additions are stored in the temporary  object shown as. Finally, the result must be assigned to a  object to ensure that memory resources do not leak.

Note that other combinations of the arithmetic operations are also possible. In particular, when other higher precedence operators, such as binary multiplication and division are used, objects may be created in different order. For the sake of simplicity, only binary addition is shown in the examples and parentheses are used to enforce precedence. For instance, consider the following order of execution.

To obtain the above behavior, both the classes ( and  ) are implemented in an idiomatic way as shown below.

Some highlights of the above code are given here. objects are created only as a result of  additions. Addition of two  objects results in a freshly allocated   object. On the other hand, when any one of the objects being added are of  type, the result is stored in the memory referenced by the temporary.

constructor allocates memory but destroys it only when  is true. destructor responsible for freeing memory. Unlike copy-constructor of,   copy-constructor does a shallow copy. However, as mentioned before, construction of  from   does a deep copy with its exclusive memory.

is a key function in this idiom. Note that the result of the addition is stored in the temporary object itself thereby avoiding another allocation. The  that takes a   object as a parameter is interesting because it accepts   object by-value. This is necessary because an addition of two temporary objects should result into only one temporary object and the other one must be destroyed. objects do manage their memory, therefore, one of the objects is explicitly destroyed using. This would not have been possible if right-hand-side  is bound to a const-reference.

The  class is implemented in terms of. Construction of  from another   does an allocation and copy. On the other hand, construction of  from a   simply copies the pointers because   does not delete data. The same rules are applicable to the assignment operators of the  class. Finally,  destructor simply changes the   flag to   resulting into deleting the memory. To handle some rarely occurring cases correctly, assignments to a  object are also handled. An assignment from a  is simply a copy operation whereas an assignment from a   class requires destroying one of them and doing a shallow copy of the pointers.

Caveats

This idiom has some serious drawbacks.
 * The result of computation must be assigned to a derived class object ( object). Otherwise there is definite resource leak in the program. Such a convention is usually very hard to maintain.
 * As a consequence, this idiom is not even basic exception safe. If any intermediate memory allocation operation throws an exception, it is very likely that there would be a resource leak.

Known Uses
The TBCI Library

Related Idioms

 * Move Constructor
 * Computational Constructor
 * Resource Acquisition Is Initialization

title: More C++ Idioms/Temporary Base Class


text:
More C++ Idioms/Curiously Recurring Template Pattern

= Curiously Recurring Template Pattern =

Intent
Specialize a base class using the derived class as a template argument.

Also Known As

 * CRTP
 * Mixin-from-above
 * Static polymorphism
 * Simulated dynamic binding
 * Upside-down Inheritance

Motivation
To extract out a type independent but type customizable functionality in a base class and to mix-in that interface/property/behavior into a derived class, customized for the derived class.

Solution and Sample Code
In CRTP idiom, a class T inherits from a template that specializes on T. This is valid only if the size of X can be determined independently of T. Typically, the base class template will take advantage of the fact that member function bodies (definitions) are not instantiated until long after their declarations, and will use members of the derived class within its own member functions, via the use of a, e.g.:

C++23
C++23 added a new feature called explicit object parameter, which allows you to pass the object a method is called on as the first parameter of a method instead of. When calling the method, as with all function calls, upcasts are only performed if necessary, making it possible to change the behavior of a method for derived classes without overriding it by using a method template or. If the CRTP base class you would have written only has non-static methods, this removes the need to pass T as a template parameter, making it similar to deriving from an ordinary base class. One benefit of this approach is that if  is a base class of , the mixin methods of Derived will use   methods rather than   methods. Another is that it makes const and non-const method overloads unnecessary because the explicit object parameter can bind to const and non-const references if a constraint is not used to prevent this.

Known Uses
Barton-Nackman trick

Related Idioms

 * Parameterized Base Class Idiom
 * Barton-Nackman trick


text:
More C++ Idioms/Parameterized Base Class

= Parameterized Base Class =

Intent
To abstract out an aspect in a reusable module and combine it in a given type when required.

Also Known As

 * Mixin-from-below
 * Parameterized Inheritance

Motivation
A certain aspect can be abstracted out from requirements and be developed as templates (e.g., object serialization). Serialization is a cross-cutting concern that many classes/POD types in an application may have. Such a concern can be abstracted out in a manageable reusable module. By addition of an aspect, substitutability with the original type is not broken so another motivation is to have a IS-A (public inheritance) or WAS-A (private inheritance) relationship with the type parameter.

Solution and Sample Code
Serializable  can be used polymorphically as a T as well as a ISerializable. Above example works correctly only if T is a user-defined POD type without pointers.

Related Idioms

 * Curiously Recurring Template Pattern


text: More C++ Idioms/Computational Constructor for Return Value Optimization


text:
More C++ Idioms/Type Safe Enum

= Type Safe Enum =

Intent
Improve type-safety of native enum data type in C++.

Also Known As
Typed enums

Motivation
Enumerations in C++03 are not sufficiently type-safe and may lead to unintended errors. In spite of being a language-supported feature, enums also have code portability issues due to different ways in which different compilers handle the corner cases of enumerations. The problems surrounding enumerations can be categorized in 3 ways :

 * Implicit conversion to an integer
 * Inability to specify the underlying type (prior to c++11)
 * Scoping issues

C++03 enumerations are not devoid of type safety, however. In particular, direct assignment of one enumeration type to another is not permitted. Moreover, there is no implicit conversion from an integer value to an enumeration type. However, most unintended enumeration errors can be attributed to its ability to get automatically promoted to integers. For instance, consider the following valid C++03 program. Only a few compilers such as GNU g++ issue a warning to prevent unintended errors like below.

Other problems with C++03 enums are their inability to specify the underlying representation type to hold the values of enumerators. A side effect of this underspecification is that the sizes and the signedness of the underlying type vary from compiler to compiler, which leads to non-portable code. Finally, the scoping rules of C++03 may cause inconvenience. For instance, two enumerations in the same scope can not have enumerators with the same name.

Type safe enum idiom is a way to address these issues concerning C++03 enumerations. Note that enum class in C++11 eliminates the need of this idiom.

Solution and Sample Code
Type safe enum idiom wraps the actual enumerations in a class or a struct to provide strong type-safety.

In the above solution, the actual enumerations are wrapped inside color_def and shape_def structures. To obtain a safe enumeration type from the definitions, safe_enum template is used. safe_enum template makes use of the Parameterized Base Class idiom i.e., it inherits publicly from the def parameter inself. As a result, the enumerations defined in the definitions are available in the safe_enum instantiation.

safe_enum template also supports a way to specify the underlying type (inner) used to hold values of the enumerators. By default it is the same as the enumeration type in its definition. Using explicit underlying representation type as the second type parameter, the size of the safe_enum template instantiation can be controlled in a portable way.

safe_enum template prevents automatic promotion to integers because there is no conversion operator in it. Instead, it provides underlying function, which can be used to retrieve the value of the enumerator. Overloaded operators are also provided by the template to allow simple comparisons and total ordering of the type-safe enumerators.

Iterating over enumerations

In some cases where enumerations are all contiguous values, iteration over the entire set of enumeration is also possible. Strictly speaking, iteration is not a part of the idiom, but it is a useful enhancement. Following code shows the enhancements needed to add iteration capability. A static array of safe_enums is created for each instantiation of safe_enum class. The array is populated by the initialize function with the original enumeration values. Note that enumeration values are assumed to be contiguous in the initialize function. Once the array is initialized, iteration is simply traversal from beginning to the end of the static array. The begin and end functions return iterators to the beginning and (one past) the end of the array.

Related Idioms

 * Parameterized Base Class

title: More C++ Idioms/Type Safe Enum


text:
More C++ Idioms/Fast Pimpl

Intent
Increase performance of Handle Body idiom.

Motivation
Regular PIMPL idiom achieves "Compilation Firewall" by sacrificing performance. Fast PIMPL attempts to reduce the overhead of heap allocation and non-local memory access by composing the implementation object within the original interface object.

Solution and Sample Code
Note that handle to instance of Wrapped class is not required. To reduce memory footprint Wrapped class can be accessed by a helper function instead.

Known Uses
This pattern is frequently used in high performance or memory constrained environments when implementation is desired to be unseen or decoupled.

Related Idioms

 * Handle Body (aka pimpl)

title: More C++ Idioms/Fast Pimpl


text:
More C++ Idioms/Non-Virtual Interface

= Non-Virtual Interface =

Intent

 * To modularize/refactor common before and after code fragments (e.g., invariant checking, acquiring/releasing locks) for an entire class hierarchy at one location.

Also Known As

 * Template Method - a more generic pattern, from the Gang of Four's Design Patterns book.

Motivation
Pre- and post-condition checking is known to be a useful object-oriented programming technique particularly at development time. Pre- and post-conditions ensure that invariants of a class hierarchy (and in general an abstraction) are not violated at designated points during execution of a program. Using them at development time or during debug builds helps in catching violations earlier. To maintain consistency and ease of maintenance of such pre- and post-conditions, they should be ideally modularized at one location. In a class hierarchy, where its invariants must be held before and after every method in the subclasses, modularization becomes important.

Similarly, acquiring and releasing locks on a data structure common to a class hierarchy can be considered as a pre- and post-condition, which must be ensured even at production time. It is useful to separate the responsibility of lock acquiring and releasing from subclasses and put it at one place - potentially in the base class.

Solution and Sample Code
Non-Virtual Interface (NVI) idiom allows us to refactor before and after code fragments at one convenient location - the base class. The NVI idiom is based on 4 guidelines outlined by Herb Sutter in his article named "Virtuality"[2]. Quoting Herb:

 * Guideline #1: Prefer to make interfaces nonvirtual, using Template Method design pattern.
 * Guideline #2: Prefer to make virtual functions private.
 * Guideline #3: Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected.
 * Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual. - Quote complete.

Here is some code that implements the NVI idiom following the above 4 guidelines.

The above implementation of the base class captures several design intents that are central to achieving the benefits of the NVI idiom. This class intends to be used as a base class and therefore, it has a virtual destructor and some pure virtual functions (read_from_impl, write_to_impl), which must be implemented by all the concrete derived classes. The interface for clients (i.e., read_from and write_to) is separate from the interface for the subclasses (i.e. read_from_impl and write_to_impl). Although the read_from_impl and write_to_impl are two private functions, the base class can invoke the corresponding derived class functions using dynamic dispatch. These two functions give the necessary extension points to a family of derived classes. However, they are prevented from extending the client interface (read_from and write_to). Note that, it is possible to call interface for clients from the derived classes, however, it will lead to recursion. Finally, the NVI idiom suggests use of exactly one private virtual extension point per public non-virtual function.

Clients invoke only the public interface, which in turn invokes virtual *_impl functions as in the Template Method design pattern. Before and after invoking the *_impl functions, lock operations and invariant checking operations are performed by the base class. In this way, hierarchy wide before and after code fragments can be put together at one place, simplifying maintenance. Clients of the Base hierarchy still get polymorphic behavior even though they don't invoke virtual functions directly. Derived classes should ensure that direct access to the implementation functions (*_impl) is disallowed to the clients by making them private in the derived class as well.

Consequences
Using the NVI idiom may lead to fragile class hierarchies if proper care is not exercised. As described in [1], in Fragile Base Class (FBC) interface problem, subclass's virtual functions may get accidentally invoked when base class implementation changes without notice. For example, the following code snippet (inspired by [1]) uses the NVI idiom to implement CountingSet, which has Set as a base class.

The above class hierarchy is fragile in the sense that during maintenance, if the implementation of the addAll function (indicated by (1)) is changed to call public non-virtual add function for every integer from begin to end, then the derived class, CountingSet, breaks. As addAll calls add, the derived class's extension point add_impl is called for every integer and finally addAll_impl is also called counting the range of integers twice, which silently introduces a bug in the derived class! The solution is to observe a strict coding discipline of invoking exactly one private virtual extension point in any public non-virtual interface of the base class. However, the solution depends on programmer discipline and hence difficult to follow in practice.

Note how the NVI idiom treats each class hierarchy as a tiny (some may like to call trivial) object-oriented framework, where inversion of control (IoC) flow is commonly observed. Frameworks control the flow of the program as opposed to the functions and classes written by the client, which is why it is known as inversion of control. In NVI, the base class controls the program flow. In the example above, the Set class does the required common job of insertion before calling the *_impl virtual functions (the extension points). The Set class must not invoke any of its own public interface to prevent the FBC problem.

Finally, the NVI idiom leads to a moderate degree of code bloat in the class hierarchy as the number of functions double when the NVI is applied. Size of the refactored code in the base class should be substantial to justify the use of NVI.

Related Idioms

 * Interface Class
 * Thread-Safe Interface, from Pattern-Oriented Software Architecture (volume 2) by Douglas Schmidt et al.
 * Public Overloaded Non-Virtuals Call Protected Non-Overloaded Virtuals

title: More C++ Idioms/Non-Virtual Interface


text: More C++ Idioms/Storage Class Tracker

title: More C++ Idioms/Storage Class Tracker


text:
More C++ Idioms/Attach by Initialization

= Attach by Initialization =

Intent
Attach a user-defined object to a framework before program execution begins.

Also Known As

 * Static-object-with-constructor

Motivation
Certain application programming frameworks, such as GUI frameworks (e.g., Microsoft MFC) and object request brokers (e.g., some CORBA implementations) use their own internal message loops (a.k.a. event loops) to control the entire application. Application programmers may or may not have the freedom to write the application-level  function. Often, the  function is buried deep inside the application framework (e.g,   in case of MFC). Lack of access to  keeps programmers from writing application-specific initialization code before the main event loop begins. The attach-by-initialization idiom is a way of executing application-specific code before the execution of a framework-controlled loop begins.

Solution and Sample Code
In C++, global objects and static objects in the global namespace are initialized before  begins. These objects are also known as objects of static storage duration. This property of objects of static storage duration can be used to attach an object to a system if programmers are not allowed to write their own  function. For instance, consider the following (smallest possible) example using Microsoft Foundation Classes (MFC):

The above example creates a window titled "Hello, World!" and nothing more. The key thing to note here is the global object  of type. The  object is default-initialized before the execution of. As a side-effect of initializing the objects, the constructor of  is also called. The  class is a part of the framework and invokes constructors of several other classes in the framework. During the execution of these constructors, the global object is attached to the framework. The object is later on retrieved by, which is the MFC equivalent of the regular. The  member function is shown just for the sake of completeness and is not an integral part of the idiom. This function is called after  begins execution.

Global and static objects can be initialized in several ways: default constructor, constructors with parameters, assignment from a return value of a function, dynamic initialization, etc.

Caveat

In C++, objects in the same compilation unit are created in order of definition. However, the order of initialization of objects of static storage duration across different compilation units is not well defined. Objects in a namespace are created before any function/variable in that namespace is accessed. This may or may not be before main. Order of destruction is the reverse of initialization order but the initialization order itself is not standardized. Because of this undefined behavior, the static initialization order problem comes up when a constructor of a static object uses another static object that has not been initialized yet. This idiom makes it easy to run into this trap because it depends on an object of static storage duration.

Known Uses

 * Microsoft Foundation Classes (MFC)


text:
More C++ Idioms/Base-from-Member

= Base-from-Member =

Intent
To initialize a base class from a data-member of the derived class.

Motivation
In C++, base classes are initialized before any member of the derived class. The reason for this is that members of a derived class may use the base part of the object. Therefore, all the base parts (i.e., all base classes) must be initialized before members of the derived class. Sometimes, however, it becomes necessary to initialize a base class from a data member that is available only in the derived class. It sounds contradictory to the rules of C++ language because the parameter (a member of derived class) that is passed to the base class constructor must be fully initialized. This creates a circular initialization problem (an infinite regress).

The following code, obtained from the Boost libraries, shows the problem.

The above code snippet shows a case where the programmer is interested in customizing the  class. They do so in  by inheriting from. The  class is used as a member in   class, which is a kind of. The  class, however, needs a pointer to a   class, or its derived class. The type of pointer to  is suitable but passing it makes sense only if   is initialized. However, it won’t be initialized unless all base classes are initialized. Hence the infinite regress. The base-from-member idiom addresses this problem.

Solution and Sample Code
This idiom makes use of the fact that base classes are initialized in the order they are declared. The derived class controls the order of its base classes, and in turn, controls the order in which they are initialized. In this idiom, a new class is added just to initialize the member in the derived class that is causing the problem. This new class is introduced in the base-class-list before all other base classes. Because the new class comes before the base class that needs the fully constructed parameter, it is initialized first and then the reference can be passed as usual. Here is the solution using base-from-member idiom.

The  class is the newly introduced class that now has the   member. The  class inherits from this new class and adds it before   in its base class list. This ensures that  is initialized before   and the pointer can be safely passed to it's constructor.

Known Uses

 * Boost Base from Member

title: More C++ Idioms/Base-from-Member


text:
More C++ Idioms/Thin Template

= Thin Template =

Intent
To reduce object code duplication when a class template is instantiated for many types.

Motivation
Templates are a way of reusing source code, not object code. A template can be defined for a whole family of classes. Each member of that family that is instantiated requires its own object code. Whenever a class or function template is instantiated, object code is generated specifically for that type. The greater the number of parameterized types, the larger the generated object code. Compilers only generate object code for functions for class templates that are used in the program, but duplicate object code could still pose a problem in environments where memory is not really abundant. Reusing the same object code could also improve instruction cache performance and thereby application performance. Therefore, it is desirable to reduce duplicate object code.

Solution and Sample Code
Thin template idiom is used to reduce duplicate object code. Object code level reusable code is written only once, generally in a base class, and is compiled in a separately deployable .dll or .so file. This base class is not type safe but type safe "thin template" wrapper adds the missing type safety, without causing much (or any) object code duplication. The base class may be fat: it may contain an arbitrary amount of code. Because the base class uses only non-inline functions, its code is only generated once. But because the casting is encapsulated in the inline functions in the class template, the class is typesafe to its users. The templated class is thin, because it does not generate much code per template instantiation.

Known Uses
Symbian OS relies on this idiom a lot. For example, where CArrayFixBase does all the work

title: More C++ Idioms/Thin Template


text: More C++ Idioms/Object Template

title: More C++ Idioms/Object Template


text:
More C++ Idioms/Const auto ptr

= Const auto_ptr =

Intent
To prevent transfer of ownership of a held resource. Note: auto_ptr has been deprecated and is replaced by shared_ptr, unique_ptr and weak_ptr in C++11, thereby this idiom is no longer suggested.

Motivation
Often it is desirable to enforce a design decision of non-transferable ownership in code and enforce it with the help of compiler. Ownership in consideration here is of any resource such as memory, database connections and so on. const auto_ptr idiom can be used if we don't want ownership of the acquired resource to be transfered outside the scope or from one object to the another.

auto_ptr without any cv-qualifier (fancy name for const and volatile) has move semantics as described in the Move Constructor idiom. It basically means that ownership of memory is unconditionally transferred from right hand side object to the left hand side object of an assignment, but it ensures that there is always a single owner of the resource. const auto_ptr can prevent the transfer.

Solution and Sample Code
Declare the auto_ptr holding memory resource as const. Compiler issues a warning here because the copy-constructor of yptr is not really a copy-constructor but in fact it is a move constructor, which takes a non-const reference to an auto_ptr, as given in Move Constructor idiom. A non-const reference can't bind with a const variable and therefore, compiler flags an error.

Consequences

 * An undesirable consequence of const auto_ptr idiom is that compiler can't provide a default copy-constructor to a class that has a const auto_ptr member in it. This is because the compiler generated copy-constructor always takes a const RHS as a parameter, which can't bind with a non-const move constructor of auto_ptr. The solution is to use Virtual Constructor idiom or use boost::scoped_ptr, which explicitly prohibits copying by denying access to assignment and copy-constructor.

Related Idioms

 * Move Constructor

title: More C++ Idioms/Const auto ptr


text:
More C++ Idioms/Safe bool

= Safe Bool =

Intent
To provide boolean tests for a class but restricting it from taking participation in unwanted expressions.

Motivation
User provided boolean conversion functions can cause more harm than benefit because it allows them to participate in expressions you would not ideally want them to. If a simple conversion operator is defined then two or more objects of unrelated classes can be compared. Type safety is compromised. For example,

Solution and Sample Code
Safe bool idiom allows syntactical convenience of testing using an intuitive if statement but at the same time prevents unintended statements unknowingly getting compiled in. Here is the code for the safe bool idiom.

Reusable Solution

There are two plausible solutions: Using a base class with a virtual function for the actual logic, or a base class that knows which function to call on the derived class. As virtual functions come at a cost (especially if the class you're augmenting with Boolean tests doesn't contain any other virtual functions). See both versions below: Here's how to use safe_bool: In C++, address of protected members functions can't be taken in a derived class. Derived class could be a standard class, a class template or a specialization of a class template. Some implementations of safe bool idiom declare safe_bool_base::this_type_does_not_support_comparisons as protected, address of which can't be taken in the derived class - a requirement in reusable safe bool idiom.

An insightful discussion on the boost mailing list initiated by Krzysztof Czainski resulted in an implementation of safe bool idiom using CRTP as well as another using macros.

C++11
The C++11 standard provides explicit conversion operators as a parallel to explicit constructors. This new feature solves the problem in a clean way.

title: More C++ Idioms/Safe bool


text:
More C++ Idioms/Iterator Pair

= Iterator Pair =

Intent
Specify a range of data values without worrying about the underlying data structure used by the data values.

Also Known As
Sometimes this is referred to as an Iterator Range.

Motivation
It is well understood that it is useful to create a vector from another vector using a copy constructor. Similarly, it is useful to create a vector from a vector using Coercion by Member Template idiom applied on a member template constructor. A code example is given below.

The vector interface is still not flexible enough for some needs. For example, A vector can't create itself from a list or a set or a POD array. Iterator-pair is an idiom that addresses this challenge. It is based on the Iterator design pattern (obviously!) Iterator pattern intent: Provide an object which traverses some aggregate structure, abstracting away assumptions about the implementation of that structure.

Solution and Sample Code
A pair of iterators is used to designate a beginning and an end of a range of values. By virtue of the iterator design pattern whoever (in our example vector) uses iterator pair idiom can access the range without worrying about the implementation of the aggregate data structure. The only requirement is that the iterators should expose a fixed, minimal interface such as a pre-increment operator.

Iterator-pair idiom is often combined with member templates because the exact type of the iterators is not known apriori. It could be set::iterator or list::iterator or a POD array. Irrespective of the type, any generic algorithm written in terms of the iterator pairs works. It is often useful to indicate the concept that iterator types are supposed to model. In the example above, the iterators are required to model at least the InputIterator concept. More information about iterator categories (tags) and their uses are described in Tag Dispatching idiom.

Sometime iterator pair idiom is unavoidable. For example, to construct a std::string from a buffer of characters with embedded null characters iterator-pair idiom is unavoidable.

Known Uses
All standard containers

Related Idioms

 * Coercion by Member Template
 * Tag Dispatching

title: More C++ Idioms/Iterator Pair


text:
More C++ Idioms/Scope Guard

= Scope Guard =

Intent

 * To ensure that resources are always released in face of an exception but not while returning normally
 * To provide basic exception safety guarantee

Motivation
Resource Acquisition is Initialization (RAII) idiom allows us to acquire resources in the constructor and release them in the destructor when scope ends successfully or due to an exception. It will always release resources. This is not very flexible. Sometime we don't want to release resources if no exception is thrown but we do want to release them if an exception is thrown.

Solution and Sample Code
Enhance the typical implementation of the Resource Acquisition is Initialization (RAII) idiom with a conditional check.

Known Uses

 * boost::mutex::scoped_lock
 * boost::scoped_ptr
 * std::auto_ptr
 * ACE_Guard
 * ACE_Read_Guard
 * ACE_Write_Guard
 * ACE_Auto_Ptr
 * ACE_Auto_Array_Ptr

Related Idioms

 * Resource Acquisition Is Initialization (RAII)

title: More C++ Idioms/Scope Guard


text:
Chess Opening Theory/1. e4/1...e5/2. Nf3/2...Nc6/3. Bb5/3...a6/4. Ba4/4...Nf6/5. O-O/5...Nxe4/6. d4/6...b5/7. Bb3/7...d5

=Ruy Lopez Open Defence=

Black's position is now reasonable. White must reclaim the lost pawn now or have nothing to show for its loss. As 8. Nxe5 would allow Black to exchange off the knight that is currently obstructing his c-pawn, 8. dxe5 is preferable. 8. Re1 would grant Black equality.


text:
More C++ Idioms/Move Constructor

= Move Constructor =

Intent
To transfer the ownership of a resource held by an object to another object in C++03. Note: In C++11, move-constructors are implemented using the built-in rvalue reference feature.

Also Known As

 * Colvin-Gibbons trick
 * Source and Sink Idiom

Motivation
Some objects in C++ exhibit so-called move semantics. For example,. In the code that follows,  ceases to be useful after the creation of object. The copy constructor of  modifies its argument, and hence it does not take a   reference as a parameter. It poses no problem in the above code because object  is not a   object. But it creates a problem when a temporary is involved.

When a function returns an object by value and that returned object is used as an argument to a function (for example to construct another object of the same class), compilers create a temporary of the returned object. These temporaries are short lived and as soon as the statement is executed, the destructor of the temporary is called. The temporary therefore owns its resources for a very short time. The problem is that temporaries are quite like  objects (it makes little sense to modify a temporary object). Therefore, they can not bind to a non-const reference and as a result, can not be used to call the constructor taking a non- reference. A move constructor can be used in such cases.

Solution and Sample Code
The move constructor/assignment idiom plays an important role in the code snippet shown next. The function  returns the object by value i.e., a temporary object is returned. Though  does not have any copy-constructor, the construction of local variable   in   succeeds, while moving the ownership away from the temporary object.

The idiom uses a combination of three interesting and standard features of C++.

 * A copy-constructor need not take its parameter by  reference. The C++ standard provides a definition of a copy-constructor in section 12.8.2. Quoting -- A non-template constructor for class X is a copy constructor if its first parameter is of type ,  ,   or  , and either there are no other parameters or else all other parameters have default arguments. -- End quote.
 * A sequence of conversions via the  object is identified automatically by the compiler.
 * Non-const functions can be called on temporary objects. For instance, the conversion function  is non-const. This member conversion operator is used to modify the temporary object.

The compiler seeks a copy-constructor to initialize object. There is a copy-constructor defined but it accepts its parameter by non-const reference. The non-const reference does not bind to the temporary object return by function. Therefore, the compiler looks for other options. It identifies that a constructor that accepts a  object is provided. So it tries to identify a conversion operator that converts the  object to. As a matter of fact, such a conversion operator is also provided. Note also that the conversion operator is non-const. That's not a problem because C++ allows invoking non-const functions on temporaries. Upon invocation of this conversion function, the local  object (m) loses its resource ownership. Only the  object knows the pointer to   for a very brief period of time. Subsequently, the converting constructor (the one that takes  as a parameter) successfully obtains the ownership (object   in  ).

Let's look into the details of how temporary objects are created and used. In fact, the above steps are executed not once but twice in exactly the same way. First to create a temporary  object and later to create the final object   in. The second exceptional rule of C++ comes into play when  is being created from the temporary   object. The conversion function is called on the temporary   object. Note that it is non-const. A non-const member function can be called on a temporary object unlike real  objects. Section 3.10.10 in C++ ISO/IEC 14882:1998 standard clearly mentions this exception. More information on this exception can be found here. The conversion operator happens to be a non-const member function. Therefore, the temporary  object also loses its ownership as described above. Several temporary  objects also are created and destroyed when the compiler figures out the right sequence of conversion functions. It is possible that the compiler might eliminate certain temporaries using return value optimization (RVO). To observe all the temporaries, use --no-elide-constructors option to the gcc compiler.

This implementation of the move constructor idiom is useful to transfer the ownership of resources (e.g., heap-allocated memory) in and out of a function. A function that accepts  by-value serves as a sink function because the ownership is transferred to a function deeper inside the call-stack whereas a function that returns   by-value serves as source because the ownership is moved to an outer scope. Hence the name source-and-sink idiom.

Safe Move Constructor

Although the source-and-sink idiom is quite useful at the boundaries of a function call, there are some undesirable side-effects of the above implementation. Particularly, simple expressions that look like copy-assignment and copy-initialization do not make copies at all. For instance, consider the following code:

object  looks like it has been copy-assigned from. However, it silently steals the underlying resource from  leaving it behind as if it is default initialized. The  object no longer owns the heap allocated integer. Such behavior is quite surprising to most programmers. Moreover, generic code written assuming regular copy semantics will likely have very undesirable consequences.

The semantics mentioned above are commonly known as Move Semantics. It is a powerful optimization. However, part of the problem of this optimization, implemented in the above form, is the lack of error messages during compilation of assignment and copy-initialization of expressions that look like a copy but in fact perform a move. Specifically, implicitly copying one  from another named   (e.g.,  ) is unsafe and therefore should be indicated by an error.

Note that stealing resources from a temporary object is perfectly acceptable because they do not last long. The optimization is meant to be used on rvalues (temporary objects). Safe move constructor idiom is a way of achieving this distinction without language-level support (rvalue references in C++11).

The safe move constructor idiom prevents implicit move semantics from named objects by declaring private constructor and assignment operator functions.

Key thing to note here is that the parameter types are non-const. They bind to named objects only and not to temporary objects. This little change alone is sufficient to disable implicit moves from named objects but allow moves from temporary objects. The idiom also provides a way to do explicit move from a named object, if desired.

The  function above is also quite idiomatic. It must accept the parameter as a non-const reference to the object so that it binds to l-values only. It turns a non-const  lvalue (named object) into an rvalue (temporary object) via conversion to. Two explicit conversions are necessary inside the  function to avoid certain language quirks. Ideally, the  function should be defined in the same namespace as that of   class so that the function can be looked up using argument dependent lookup (ADL).

Function  returns a local   object. Because it is a named object,  must be used to turn it into an rvalue before returning. In, first   is initialized directly from the temporary returned by. Simple assignment to another  fails with a compiler error but explicit move works. Similarly, implicit copy to the  function does not work. Programmer must explicitly express its interest in moving the object to the  function.

Finally, it is also important that the key functions (construction from and to ) be non-throwing to guarantee at least basic exception guarantee. No exceptions should be thrown in the meanwhile, otherwise there will be resource leaks.

C++11 provides rvalue references, which support language-level move semantics, eliminating the need for the Move Constructor idiom.

Historical Alternatives

An old (but inferior) alternative is to use a  member to keep track of ownership to sneak past the const-correctness checks of the compiler. The following code shows how the  may be implemented alternatively.

This technique, however, has several disadvantages.

 * The copy constructor and copy-assignment operators do not make logical copies. On the contrary, they transfer the ownership from right hand side object to . This fact is not reflected in the interface of the second implementation of  . The first   class accepts a   object by non-const reference, which prevents the use of the object in contexts where a copy is expected.
 * The Const auto_ptr idiom, which is C++03's way of preventing transfer of ownership is simply not possible with the second implementation of the  class. This idiom depends on the fact that   auto_ptr objects cannot bind to the non-const reference parameters of the move-constructor and move-assignment operators. Making the parameters   references defeats the purpose.
 * The  flag 'owner' increases the size of the structure. The increase in size is substantial (essentially double) for classes like , which otherwise contain just a pointer. Doubling of the size is due to compiler-enforced alignment of data.

Known Uses

 * Boost.Move library
 * std::auto_ptr uses "unsafe" version of move constructor.
 * The unique_ptr C++03 emulation by Howard Hinnant uses the safe move constructor idiom.

Related Idioms

 * Resource Acquisition Is Initialization (RAII)
 * Scope Guard
 * Resource Return
 * Const auto_ptr

title: More C++ Idioms/Move Constructor