Warning: INSERT command denied to user 'dbo292345962'@'74.208.16.27' for table 'watchdog' query: INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (0, 'php', '%message in %file on line %line.', 'a:4:{s:6:\"%error\";s:12:\"user warning\";s:8:\"%message\";s:397:\"INSERT command denied to user 'dbo292345962'@'74.208.16.27' for table 'captcha_sessions'\nquery: INSERT into captcha_sessions (uid, sid, ip_address, timestamp, form_id, solution, status, attempts) VALUES (0, '690263a16dbdb533ccc65df80841c224', '54.90.188.7', 1406116708, 'comment_form', 'c76c44247053e4947ed458b97c5bd0a6', 0, 0)\";s:5:\"%file\";s:62:\"/homepages/25/d199835659/htdocs/ID/modules/captcha/captcha.inc\";s:5:\"%line\";i:99;}' in /homepages/25/d199835659/htdocs/ID/includes/database.mysql.inc on line 135
Singleton C++ | Inferno Development

Singleton C++

The Singleton C++ Design Pattern is a C++ design that creates one single instance of a class that can be used throughout multiple files and large projects.

Think of C++ Singleton like a global class that can be accessed at any moment and will be created only once, if it hasn't already been initialized.

It's a very simple concept, that is used so that you can have access to a set of variables in a class without ever initializing the class.

C++ Singleton Example

For example, a good use of singleton would be for logging. You don't want to have to make new instances of your Log class which records errors and logs to a file.

There is a tutorial on how to build a C++ log file class at ID.

You can call the log class like this:

Log::Inst()->Logging("Warning: Just a log!");

You can also initialize it using #define:

#define LOG Log::Inst("error.log")->Logging

int main(){
  LOG("This is a line of log");
  return 0;
}

See, notice how there's no initializing (like Log* log = new Log(filename); or Log log(filename);). Using the define you can have it behave like a global function.

C++ Singleton Header File

The following code will show you exactly how to program this neat C++ technique:

#include <string>
using namespace std;

class Log {
  public:
    static Log* Inst(char* filename);
    void Logging(string message);
    void Initialize();
    ~Log();
  protected:
    Log(); // constructor
  private:
    static Log* pInstance;
};

We declare an Inst() function, which will return our static Log class pointer. We have an instance called pInstance, which is our static pointer to our class. As well as the constructor and other functions.

C++ Singleton File

The cpp file (C++ file) below:

Log* Log::pInstance = NULL;

Log* Log::Inst(char* filename){
  if(pInstance == NULL){
    pInstance = new Log(filename);
  }
  return pInstance;
}

Log::Log(){ // constructor
  Initialize(); // you can ignore this function
}

I declare the instance as a null pointer. Then I define our Inst() function, which will create a new instance of Log if it isn't created yet.

Important Note:
Since the constructor is protected, you cannot create instances without using the Log::Inst() method.

Major Flaw

Important Note: You have to delete pInstance; at the end of your program otherwise it is a Memory Leak! But if you use a multi-threaded application then this method is your only solution.

Flawed Solution

If your application is single-threaded then this is the perfect solution, but if it is multi-threaded this may not work, since the new operator is thread-safe and this method is not:

Log* Log::Inst(){
  static Log inst;
  return &inst;
}

Also you can delete all the pInstance variables from class declaration and implementation.

This solution will work great with any single threaded application as static variables are destroyed automatically if your application terminates by your operating system.

Other Implementations for C++ Singleton

This is also very useful in PHP, not just C++, where you may have only one instance of a database connection (having multiple ones can cause conflict!).

Anonymous's picture

Very nice tutorial, it was

Very nice tutorial, it was just what I was looking for!

Harrison's picture

Hello, I'm curious as to why

Hello,

I'm curious as to why you are saying that one implementation is thread safe over another. I don't understand how a newed instance of the singleton is any more thread safe than static instance. From what I can tell, the only difference is that the static instance is allocated before the first call to the singleton and the newed version isn't allocated until the first call, but both would go out of scope at the same time (after main()).

Please help me understand.

Best Regards!

Anonymous's picture

Why not just declare the

Why not just declare the class as 'static' i.e. 'static class _myClass', set up some '#define' statements for easy access/reference, and call it a day. Or is that too noob-ish ?

Anonymous's picture

C++ doesn't support static

C++ doesn't support static classes.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.