Read one line from a text file

File stream is great for reading data to and from files,. Mainly because it always makes sure to close the file when the object goes out of scope, which means that we don’t need to remember to call close(), but also because it makes it possible to parse the contents of the file.

Sometimes we don’t want to parse the contents but just read the data one line at a time.



Type testing

Sometimes you want to check the type used to create a template. The standard library provides some handy routines to do this (defined in the file <type_traits>), like:

  • std::is_arithmetic<T> – this is true if the type is floating point or integral data type (like int, unsigned short, float or double). Example:
  • std::is_integral<T> – this is true if the type is an integral data type (like int, unsigned short, bool,  char or long). Example:
  • std::is_floating_point<T> – this is true if the type is floating point type (float, double or long double). Example:



Exception safety

Exception safety is about taking care of the resources that you are using, such as allocated memory or opened files, both in the happy path through your code and in the case of an exception being thrown.

The problem lies in code such as

What happens to the memory which is allocated dynamically for the array if the function bar throws an exception? What surprises many developers is that the execution will skip all code lines after the call to bar in the local function and continue with the first line in the appropriate exception handler. The line where the dynamically array is deleted (using delete[]) is not going to be called at all! This means that the code in the example above is not exception safe, when an exception is thrown then the code will leak memory.

Even though all code lines after the call to bar will be skipped, all the local variables (i.e. allocated on the stack) declared in the function foo are going to be cleaned up. And this is a feature which C++ uses to deal with exception safety. The technique is called RAII (Resource Acquisition is Initialization) and stores variables and data structures on the local stack instead of on the free store directly. Now you object that it is impossible to always store all the data on the stack, you may not know how much data you are going to need when you write the program. The size of a variable is something which you probably want to determine at run time, depending on the input data to your program.

The C++ solution to this is to store a handle to the memory that you have allocated on the free store on the local stack. When that handle goes out of scope its destructor will be called and you simply make sure that you delete all the memory used in the destructor. This is the basic concept of the standard library containers, such as vector, list or map, or the smart pointers shared_ptr and unique_ptr.  To convert the example above into exception safe code, replace the call to the dynamic memory allocation into using std::vector like this.

The instance of the vector is allocated on the local stack, but internally it will call new[] to allocate the memory for the 25 values on the free store. When the vector goes out of scope, either because the function ends or an exception is thrown, then the destructor of the vector is going to be called and this will delete all the memory that was allocated on the free store.

The C++ standard library containers and data structures all use the RAII technique for making sure that no resources are being leaked. When you create a new class you should also use the RAII technique to make sure your code is exception safe. Other developers who are using or modifying your code expect that you have taken care of releasing the resources that you are using and don’t want to worry about cleaning up the mess after you. Make the C++ code that you write developer friendly and clean up your own mess!


Move semantics

C++11 introduced the concept of move semantics, which is kind of an optimized way to copy data. When an object is moved, the contents of the object is taken over by the destination, this is different from copying the data because no valuable data is left in the old object. Move operations are therefore faster because no copying is involved, we simply move the contents of one object into another.

This changed very much how solid objects are handled in C++. Before, returning an object from a function was in many cases too expensive since all the data in the returned object would be copied to the new object. This led to the coding pattern of returning pointers to data, or to pass the return value as a parameter to a function.

However, using move semantics, we can instead return solid objects from functions without any performance penalties

The downside is that we now need to consider implementing the move constructor and move assignment operator when creating a class, in addition to the copy constructor, copy assignment operator and destructor.

Move constructor and Move assignment operator

These operators take the following form

In the move constructor and move assignment operator, you are free to steal whatever data there is in the other object. The double ample sand (&&) means an r-value reference, and this is a reference to an object which is about to die, meaning that it is going to go out of scope and we can take whatever is in it. So for example, if the class in the previous example contained a pointer to a buffer, we could take ownership of this in the move constructor, like this

However this contains a lot of duplicated code, which is very bad. A good way around this is to let the move constructor call the move assignment operator

Which is a lot shorter!

The standard containers are with C++11 also move-enabled, i.e. there are move constructor and move assignment operators defined in each of them. For example when returning a vector from a function, the created vector is moved to the outer scope and the internal pointer is moved from the dying object to the new object.

As a side note, there is sometimes a point in making a class movable by defining the move assignment operator and move constructor but prohibiting copying the class by deleting the copy constructor and copy assignment operator. An example of a class where this is done is the std::unique_ptr, which if it would allow copying would make the pointer not unique which is contrary to the whole point of the class!


  • To prevent memory leaks, always free any resource which may be present in the current object before taking over the other objects data in the move constructor and move assignment operators.
  • Always check for self-assignment in the move assignment operator.
  • Make use of the move assignment operator in the move constructor to remove redundancy.
  • If you define a move constructor, then also add a move assignment operator (see the C++ core guidelines).

Variables on the stack

I think one very underused feature in C++ today is simply storing objects on the stack. Many developers who have started writing C# or Java are used to always using new to declare a variable and do the same thing when they are writing C++. And when they later learn that you should never write a naked new, they instead start using unique_ptr or shared_ptr to manage the lifetime of their objects. What they are forgetting is that many times is it sufficient to simply store the instance that you are creating on the stack as a solid object, either as a member of a class or in the local function scope.

The standard library does this all the time, you write

never ever

If you are certain what type of object you need and when you need it, then simply put it on the local stack!

For often called methods you will get a performance increase by doing this since the allocation of an object on the free store takes some time (new has to locate a free portion of memory to allocate).

The exceptions where you don’t want to allocate the object on the local stack include cases where you may want polymorphic behavior, or the class contains large amounts of data making the object too large for the stack.


Why should I use nullptr instead of NULL?

C++11 introduced the new keyword nullptr which is used to indicate a null pointer. This is different from the old NULL which was just a zero (usually an integer).

To understand why nullptr was introduced, consider the following example:

the developer probably intended to call the overload of f taking a pointer. However, since NULL is not a pointer but an integer, the overload of f taking an integer is going to be called.

If the developer instead wrote:

then the code would be much more clear in its intent.


Why you should always use a virtual destructor

Virtual destructors are a must when you can delete an object through a pointer to a base class. Let me explain.

Say that you have a simple base class:

and a class deriving from the BaseClass with the addition of a resource which is supposed to be managed using RAII:

now what happens when you use this class:

since the base class doesn’t have a virtual destructor and ‘obj’ is pointing to a BaseClass, not to a DerivedClass, then the destructor of BaseClass is going to be called, but not the destructor of DerivedClass!! This means that the managed resource in DerivedClass is not going to be deleted properly when the object is deleted and thus we have a memory leak!

If instead the BaseClass would have a virtual destructor, like this:

then the constructors would be called in both the base class and the derived class and all contents will be correctly released.


Beginning templates

Templates are a terrific functionality in C++ which is used way too little! A template is a pattern for how a class or function taking a particular type should be created.  Lets say that you need a class which holds a stack of integers, you can simply create this as a regular class. If you later discover that you also need a class which holds a stack of  strings then you are forced to create a new class which does exactly the same thing but just using a different type of data. Creating two classes which does exactly the same thing is really wasting your time as a developer! The solution here is to create a template class; by doing so you create a pattern for how your stack class should work, but you don’t say the exact type that you will be working on.

To make a template class representing a stack, simply add the template keyword when declaring the class:


Template function

Just like you can create a template class, it is also possible to make a template function where the type of the inputs is determined at compile time, when the function is being called. Say that you want to create a function to swap two variables, you could either create one function to swap two integers

and then create an almost identical overload taking two doubles, one overload taking two strings, etc. Or you could just create one template function:

To call the template swap you don’t need to explicitly give the type of the variables (as you have to do when instantiating a template class):

Sometimes however, you may want to help the compiler determining the type of the variable. Say that you are calling a function with a literal string where the compiler would generate the template function with the type char* but you would much rather have the template function work on std::string. Then you can either tell the compiler that the type of the template function is std::string, or promote the literal string into a std::string;




Metaprogramming in C++ (a.k.a template metaprogramming) uses the fact that templates are instantiated at compile time an not at run time. This makes it possible to create a template which calculates a value at return time, a value which can then be used as a constant in the rest of the program.

Say that we create a template struct which only contains a single value

the definition of the value is recursive and refers to the calculation of the factorial of a value one-less than the requested value. However, this will not in itself compile since the compiler will get stuck in an infinite loop trying to calculate the factorial of one-less than the value eventually crashing the compilation. To stop the compiler it must be given a stopping condition, a special case where we explicitly tell the compiler what the value of the factorial is. This is done like this:

And to calculate the value of the factorial, you simply need to create an instance of the template:


See also the C++ book:


Template Specialization with a constant value

Sometimes you want to create a template based not on a type but using a specific value as input. In languages like C# and Java is this not possible, but in C++ is it allowed.

This can be done like this: