Singleton done right in C++ 11

Today searching the internet I’ve found a “cool” and simple method to create a safe singleton that performs well in multithreading environment.

With a small amount of lines you can achieve both: safe initialization and multithreading safety.

class Singleton {
     static std::once_flag onceFlag;
     static Singleton* instance;
public:
     static Singleton& getInstance(){
          std::call_once(onceFlag, []{
               instance = new Singleton();
          });
          return *instance;
     }

private:
     Singleton(){};
}

 

As c++ documentation says the:

  • The class std::once_flag is a helper structure for std::call_once.
    An object of type std::once_flag that is passed to multiple calls to std::call_once allows those calls to coordinate with each other such that only one of the calls will actually run to completion.
    std::once_flag is neither copyable nor movable.
  • The std::call_once executes the Callable object f exactly once, even if called from several threads.

 

Having this in mind stay save and use singleton in a safe way!

Happy coding!

The PIMPL idiom

The purpose

Remove compilation dependencies on internal class implementations and improve compile times.

The story behind

When a header file changes, any files that #include that file will need to be recompiled. In the case of a class header, this is true even if those changes only apply to private members of the class. The PIMPL idiom hides private members from any users of the header file, allowing these internal details to change without requiring recompilation of the client code.

Lines 5–17 define a class, foo, to which we have applied the PIMPL idiom. This class definition includes only the public interface of the class and a pointer to the internal implementation. We use a std::unique_ptr (line 16) to ensure the lifetime of the implementation is managed correctly, which we initialise in foos constructor (line 35).

While the internal implementation class, impl, is declared in the header file on line 15, its definition appears in the implementation file on lines 22–32. This allows the class definition to change without requiring users of foo to recompile.

We have explicitly defaulted foo’s destructor on line 40, which is necessary because the destructor needs to be able to see the complete definition of impl (in order to destroy the std::unique_ptr). Note that we have also explicitly defaulted the move constructor and assignment operator on lines 42–43 so that foo can be moved. To make foo copyable, we must also implement the copy constructor and assignment operator.

Note: std::make_unique was introduced in C++14. For C++11, you can roll your own implementation.

 

Brief example

// foo.h - header file
#include <memory>
class foo
{
    public:
        foo();
        ~foo();
        foo(foo&&);
        foo& operator=(foo&&);
    private:
        class impl;
        std::unique_ptr pimpl;
};
// foo.cpp - implementation file
class foo::impl
{
    public:
        void do_internal_work()
        {
            internal_data = 5;
        }
    private:
        int internal_data = 0;
};
foo::foo()
    : pimpl{std::make_unique()}
{
    pimpl->do_internal_work();
}
foo::~foo() = default;
foo::foo(foo&&) = default;
foo& foo::operator=(foo&&) = default;

 

Inheritance in C++

The question:

I looked and couldn’t find a good explanation of the difference between public, private, and protected inheritance in C++. All of the questions I’ve found deal with specific cases. What is the difference in general?

The answer:

There are three accessors that I’m aware of: public, protected and private.

Lets take the following example:

class Base {
    public:
        int publicMember;
    protected:
        int protectedMember;
    private:
        int privateMember;
};

Everything that is aware of Base is also aware that Base contains publicMember. Only the children (and their children) are aware that Base contains protectedMember. No one but Base is aware of privateMember. By is aware of, I mean acknowledge the existence of, and thus be able to access.

The same happens with public, private and protected inheritance. Let’s consider a class Base and a class Child that inherits from Base.

  • If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base.
  • If the inheritance is protected, only Child, and its children, are aware that they inherit from Base.
  • If the inheritance is private, no one other than Child is aware of the inheritance.

Testarea unui singleton folosind Mock Object

Problema

De multe ori testarea singleton-urilor este una foarte anevoioasa. Folosirea acestui pattern pe langa ca aduce multa simplitate in ceea ce priveste accesul la variabilele protejate de singleton ingreuneaza testarea codului.

Urmatorul cod prezinta solutia clasica, si nu neaparat cea mai buna, de implementare a unui singleton:


class Singleton
{
  public:
    static Singleton* getInstance()
    {
       if (!instance)
       {
          instance = new Singleton;
       }
       return instance;
    }

  private:
    Singleton(){}
    static Singleton* instance;
};

Pentru a utiliza acest singleton in cadrul altor clase avem de facut fie Singleton::getInstance() sau folosind tehnica de Dependency Injection. Continue…

Factory Method Design Pattern

Dupa singleton, un alt pattern destul de des folosit in crearea obiectelor este cel denumit “factory method”. Pe scurt acesta izoleaza partea de creare si parametrizare a unui obiect intr-o metoda statica ce are rolul, initial, de a crea obiectul iar mai apoi de a-l parametriza facandu-l gata pentru a fi utilizat. Continue…

Constrangeri in realizarea unei baze de date MySQL

Pana nu demult si eu pot sa spun ca atunci cand realizam o baza de date lucram dupa ureche. Daca mi se parea ca ceva nu e cum ar trebui modificam dupa propriul gust si simt cu increderea suficienta ca voi obtine ce doresc.Un mod ciobanesc de a face treaba, dar am reusit sa o fac si asa. Asa ca am sa incadrez aceasta etapa a proiectarii in categoria  “Asa am procedat.

Sa stiti ca facultatea este buna la ceva mai ales cand ce alegi in sa faci in cadrul cursurilor optionale consideri cu tarie ca iti va fi de folos pe viitor, si nu te indrepti cu scarba catre sala de curs sau de laborator cu gandul “ce vrea boul asta de la noi?” sau “cu ce prostii incearca sa ne impresioneze azi?”.

Avand in vedere ca domeniul de programare web e in tot mai mare crestere, cerintele pentru oameni care sunt atrasi de acest domeniu sunt tot mai ridicate nu am ramas pasiv la acest lucru si stiind ca o materie care poate sa imi descreteasca putin fruntea ar fi “B(aze de) D(ate)” am ales-o fara nici un moment de framantare azi vara ca materie optionala in acest an. Zis si in continua facere pana in saptamana 14. Continue…