Singleton implementation in Visual Studio C++ sample project

In this post I will create an implementation of the Singleton design pattern in a Visual Studio C++ (2017)  project, my sample has passed the sonar quality check  (it’s the case of all take4make sample).

This is the structure of the c++ project :

NB: thanks to Microsoft for making available the visual studio version 2017 free for learning purpose.

Basically I create Singleton class [header= Singleton.hpp implementation Songleton.cpp ]  and Caller.cpp that use the Singleton class

So to succeed  the C++ Singleton class implementation I need to answer these 2 questions.

How  to instantiate the singleton class only one time during execution life (in other words  how to  make impossible to instantiate more than one instance  )?

How to get access on the alone singleton instance from every where?

So we need to create Singleton class with a private constructor (see Singleton.hpp) so that it will be impossible to instantiate it by other c++ source file. Also we need to create a static attribute of type Singleton MyInstance which will hold the unique instance reference. Last thing we will create static method GetInstance() that check if MyInstance null and then create it using the private constructor. So GetInstance() will  take in charge  checking that we have only an alone instance of Singleton class, and return it. Also it will create if it’s not already created. This will guarantee instantiation in the first call.

Singleton.hpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#pragma once

/**
* Singleton Class tha show the singleton designe pattern implementation
*/
class Singleton
{
private:
/**
* single instance of Singleton class , it's private to avoid access directly by other classes
*/
static Singleton *MyInstance;
/**
* double number to check unicity of singleton instance
*/
double RandomNumber = 0;
/** private constructor to avoid use by other classes
* the constructor chose random number to fill randomNumber variable,
* this will show us in case of many call of singleton that it's about the same instance.
*/
Singleton();
~Singleton();

public:
/**
* get local and single instance myInstance
* it has static modifier to be the point of access
* this method create the single instance in the first call. see the Caller class to complete the vision
*/
static Singleton *GetInstance();
/**
*Simple getter of randomUmber to see if it's about many instantiation or single instantiation
*/
double GetRandomNumber();
};

 

NB: The random attribute is for test purpose in Caller.cpp to show that only one instance of singleton is created

Singleton.cpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#include "pch.h"
#include "Singleton.hpp"
#include <stdlib.h>

//constructor implementation
Singleton::Singleton()
{
//generate random number to prove for caller that there is only one instance created
Singleton::RandomNumber = rand();
}

//destructor implementation
Singleton::~Singleton()
{
//put free instruction if you did allocation in singleton class.
}
//get_instance implementation
Singleton *Singleton::GetInstance() {
//check if myInstance already created , otherwise create it and return it for callers.
if (!Singleton::MyInstance) {
Singleton::MyInstance = new Singleton;
}
return Singleton::MyInstance;
}
//get_random_number implementation
double Singleton::GetRandomNumber() {
return Singleton::RandomNumber;
}
// Instantiation t0 = null pointer
Singleton *Singleton::MyInstance = nullptr;

Caller.cpp

/*
* created in scope of www.take4make.com samples
* @author khalil CHARA
*/

#include "pch.h"
#include <iostream>
#include "Singleton.hpp"

int main()
{
Singleton *sngltnT1 = Singleton::GetInstance();
Singleton *sngltnT2 = Singleton::GetInstance();
std::cout << "sngltnT1 number is : " << sngltnT1->GetRandomNumber() << "\n";
std::cout << "sngltnT2 number is : " << sngltnT2->GetRandomNumber() << "\n";
}

// Execute the software : Ctrl+F5
// debug the software : F5

Result of the execution :

sngltnT1 number is : 41

sngltnT2 number is : 41

you can see that it’s about the same instance (for sngltnT1 and sngltnT2) because the random number is the same. if it was about different instances the random number will be different.

Down load the full project :  T4MCppSingleton

Singleton design pattern basic concept and implementations

Singleton is a creation design pattern according to Gang Of Four book ( it’ s a book made  by 4 persons  with a big knowledge of programming also called  “Design Pattern: Elements of Reusable Object-Oriented Software” )

basically a singleton is a class to instantiate one time  in  execution life. a singleton is used when we manage a class throw one and only one instance: for example to avoid waste of memory resources, or having global point of access to this one instance from all other classes in the same application . It’s very helpful for logger or configuration resources loader.

To create singleton we need to answer 2 questions:

-How to get access on the alone singleton instance from every where?

-How  to instantiate the singleton class only one time during execution life (in other words  how to  make impossible to instantiate more than one instance)?

So it does not matter if we develop in Java, C++, C#,  or Objectif C , the important thing is to ask throw the programming language the previous  2 questions

I have made 4  singleton implementations all of them are compliance with sonar quality check  and are well commented:

 

SonarQube tutorial and installation guide

In this post I will talk about SonarQube tool. I will describe installation and use in Java maven project.

I ) SonarQube Introduction

SonarQube is a tool created by sonarsource  for measuring quality of code, it support many programming languages. it’ s very helpful for the developer and team of developers.

SonarQube can generate for you a user-friendly and clear reports containing information that help  to correct , improve quality of code, like:

Duplicated code=> same code in many code parts that need to be factorized for better performance. Make your code modular: try to make each instructions block for a common feature in a separate class or  method  to be used by all other codes elements, and avoid duplicate same block of instruction in difference places. Doing so will improve performance, readability of code, and help you correct or improve the common part one time. 

-Coding standards=> code that does not respect the standard programming rules. Respecting programming standard rules is good for code visibility and performance. 

-Unit tests coverage=> bad unit test code coverage rate is not healthy. Having well covered code with unit test make recognising of regression bug very simple after any modification. 

-Code complexity=> very complicated code like nested loop is affecting performance. If you have complex feature try to split it throw many methods or function,  avoid make a lot of nested looping.

-Comments=> poor comment rate, will make your code incomprehensible (not easy to understand) for the others developers, and for you also after a while. Try at least to comment  the class and method headers as well as the code part with a high added value (important code).

-Risky parts of code=> Bug code, or code which can cause future bugs or security vulnerabilities, Try to have Zero Critical or Blocker issue, and reduce the Major and Minor issue.

NB: big Thanks to sonarsource team for this very helpful opensource tool.

II) Install SonarQube 7.4 on windows 7 machine.

  • Make sure that you have java installed in your machine : with cmd execute java -version. (if you want to install Java follow this post )
  • Download the SonarQube Community Edition from : https://www.sonarqube.org/downloads/ (download last version: we will use 7.4 in this post)
  • Unzip the directory in your desired path <your_local_path>\sonarqube-7.4
  • Open cmd and execute  StartSonar.bat located in <your_local_path>\sonarqube-7.4\bin\windows-x86-64 or <your_local_path>\sonarqube-7.4\bin\windows-x86-32  (Depending on your arch of machine x86 or x64, in my case I have x64 arch)
  • Try with any internet browser to confirm installation throw this url: http://localhost:9000
  • On your maven java project add new profile to existing profiles in the  pom.xml :

<profiles>
<profile>
<id>sonar</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>

<properties>
<sonar.host.url>http://localhost:9000</sonar.host.url>
</properties>
</profile>
</profiles>

  • With maven you can build and generate sonar report using this command :

mvn clean install sonar:sonar

  • Then go to the url http://localhost:9000/projects you will find your project analyse report:

NB: You can see for example in my singleton project that all aspect are good except test coverage, so for learning purpose and to avoid make my samples in www.take4make.com very complicated with many test unit (Dont worry I will provide some of unit test to get an idea), I will disable test coverage aspect from sonar:

  • You need to login with admin/admin (user/password) it’s the default created user. go to Administration > Analysis Scope > Coverage Exclusions. enter the  pattern  **/*.* to exclude sources from coverage test.

 

  • Once you have save the exclusion you can use maven to make report again mvn sonar:sonar

You can see now that the result is good ! I like green color.