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!

Facebookgoogle_pluslinkedinmail

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.

Facebookgoogle_pluslinkedinmail

Shared pointer – std::shared_ptr

With C++11 came a new smart pointer class, std::shared_ptr.

Copyable

The shared pointer is allocated on the stack, exactly like the std::unique_ptr, but unlike the unique pointer is it possible to copy the shared pointer. Just like the unique_ptr will the contents which the smart pointer manages be deleted once the smart pointer goes out of scope. The difference is that the resource will only be deleted when all copies of the shared_ptr have gone out of scope. That is to say that as long as there is at least one handle to the shared memory then the resource will not be cleared.

Performance

The behavior of the std::shared_ptr is in practice implemented through reference counting, creating a new copy of a std::shared_ptr increases a counter of the number of live instances and as each copy goes out of scope this counter is decreased one step. When the counter finally reaches zero then the memory is released. This reference counting means that there is a slight overhead with using a shared_ptr compared to using the unique_ptr which doesn’t have this overhead.

std::weak_ptr

There is also one danger with the shared_ptr, it is possible to create dependency chains where two objects references each other through a shared_ptr and none of the two objects will ever be cleared because there is always one reference to each (by the other object). This “bug” can be resolve by using the third smart pointer introduced in C++11, the std::weak_ptr. A weak pointer is like a copy of a shared_ptr but creating it does not increase the reference count. Therefore, when the object is only reference by weak pointers then the memory will be deleted. The weak pointer can be converted into a std::shared_ptr (which you should do before trying to use it) and if the memory referenced to by the weak_ptr has already been released then you will get an empty shared_ptr back.

Creating – std::make_shared

You create instances of shared_ptr using the helper method std::make_shared. You can of course fill in the contents of the shared pointer yourself but the make_shared method is more efficient (one memory operation less than if you do it yourself) and has the advantage that if the constructor of the object throws an exception then the std::make_shared will make sure that no memory leak occurs.

 

Facebookgoogle_pluslinkedinmail

Unique Pointer – std::unique_ptr

With C++11 came a new smart pointer class, std::unique_ptr.

This is a great class to use when you need to allocate an object which must have a life time longer than the current local scope. In old C++, this would be done by creating the object on the free store using new. It would then be up to you as a programmer to decide when the object is no longer necessary and then call delete on the pointer. The new unique pointer frees you from remembering when to call delete. The key feature of the unique pointer is that is just that, unique. There can be one and only one pointer to the managed object and no copies can ever be made. If you need a pointer which can be shared between many classes then you should instead go for shared_ptr.

The unique pointer is stored on the local scope and when it goes out of scope then the contents of the pointer will be deleted.

Non copyable

The key feature with the unique pointer is that it is unique, this means that no copies of the unique_ptr can ever be made. This has as a side effect that an object which owns a unique_ptr as a member variable can itself not be copied. If you think about it, then this is actually the same behavior as in old C++ when you instead would create a pointer using new and store the pointer as a member variable in a class. That pointer caused problems when you tried to make copies of the owning object, because who should own (and then also delete) the pointer after the copy was made? The original object or the copy? In practice this made the object not copyable unless you explicitly wrote an copy constructor and copy assignment operator. The difference is that in the old way would the program still compile and run. Modern C++ stops you from doing this, it tries to stop you from shooting yourself in the foot!

 Movable

The unique pointer is on the other hand movable, this means that it is possible to create a unique_ptr inside a function and then return the created pointer. It also means that objects owning a unique pointer will themselves also be movable without you having to do anything.

Make

C++11 introduced the std::make_shared function which made it possible to create a shared_ptr safely and easily. However, the make_unique function wasn’t added until C++14 simply because of an oversight in the review. If your compiler supports C++14 then you can create the unique pointer like this

where the parameters to the constructor of the class are passed in the parenthesis

Facebookgoogle_pluslinkedinmail

Constructor – creating the object

The constructor is a special function used to setup an object to a valid state.

  • The constructor must have the same name as the class.
  • The constructor does not have a return type.
  • There can be many constructors for the same class, the difference between them is the number and type of the parameters.

A constructor without any parameters is called the default constructor. If you don’t write a default constructor then one will be created for you automatically and setup the object with default values (which may not be what you want).

The constructor of the object is together with the destructor an important part of the RAII paradigm.

Multiple constructors

A class can have many constructors, and one common problem is that these will usually perform the same initialization of the member variables thereby creating redundant code. With the interest of keeping your code DRY, you should consider to extract the common elements into separate functions. The, in many cases, most natural solution to this would be to make the constructors call each other – but there is a pitfall here. Calling one constructor from another will only work in C++11, so if you have a compiler which supports C++11 you can do the following (called delegating constructors):

If you don’t have a C++11 compiler then the common solution is to extract a separate function which does the initialization:

 

Private Constructor

Normally is the constructor of a class a public member function. If a class has a private constructor, then it is not possible to create instances of the class anywhere else but in the class itself. This can be handy if you want all instances to be created in exactly the same way or in the same location using a static factory method.

 

 

Facebookgoogle_pluslinkedinmail

RAII – Resource Acquisition Is Initialization

Resource Acquisition is Initialization (or RAII for short, usually pronounced by simply spelling out the letters R-A-I-I) is a programming technique where we make sure that resources are cleaned up when they are no longer needed by tying a resource to an object. The resource is kept as long as the object is alive and automatically released when the object is destroyed.

The resource that is being managed can be a segment of memory, a file handle, a network socket, a database handle or anything else which there is just a limited number of in the system and which we need to make sure we close properly after we are done with it.

The way RAII works is that we tie the resource to a class. When an instance of the class is created then the constructor of the object’s class is called to create the resource (or passed the resource to be managed). When the object is later destroyed (by going out of scope) then the destructor will automatically be called and here we write the code to release the resource again.

The name is somewhat difficult and controversial, some have suggested instead calling it Scope-Bound Resource Management but this has so far not been too successful.

I think an example of what I mean is necessary here. In the example below is a segment of memory allocated (using new[]) in the constructor of the File class and the memory is released again (using delete[]) in the destructor. The neat thing here is that the destructor will automatically be called when the object goes out of scope, as is done when the function main() in the example exits.

Notice: this is only done automatically for you if the File object is allocated as a local object, this is one of the reasons why you should never use new or delete.

The benefits of RAII is that it creates:

  • exception safety: a stack object will be destroyed at the end of the enclosing scope,  also if an exception is thrown from the code after the object is created.
  •  good locality: the code for allocating the resource is in the same class as the code for releasing the resource again.
  • encapsulation: the managed resource is located inside the owning class and not accessible outside of it.

Because of its benefits is RAII used extensively throughout the standard library classes.

As an example, the following code is using old C functions to write data to a text file NOT using RAII.

In the example above we didn’t use RAII to hold on to the resource (which in this case is the file handle FILE* f). This makes the code not exception safe, if anyone would later add a function call after the file has been opened and this method throws an exception then the call to fclose will not be executed at all, leaving the file opened and locked.

A better example is to instead use the standard library to open and write to the file:

in this example does the instance of the standard library class std::ofstream which we create on the first line hold on to the file resource and when the object goes out of scope when the function ends then the file will be closed automatically for us. Notice how much shorter and cleaner this code becomes. We don’t have to worry about closing the file since this is done for us.

References

  1. Stroustrup: Why doesn’t C++ provide a “finally” construct?

 

Facebookgoogle_pluslinkedinmail