Inferno Web Development
  • Home
  • Forums
  • About
  • Links
  • Contact

Tutorials List

  • C++ Tutorials

Articles

  • Java
  • PHP
  • Photoshop
  • C#
  • C++ Qt GUI
  • C++ Win32 API
  • C++
  • MASM32
  • General News
  • JavaScript
  • Web Development
  • Windows Tweaks

Popular Tutorials

All time:

  • Website Header with 3D Fold Up / Lift Effect
  • C++ Win32 API Tutorial
  • Perfect C++ String Explode Split
  • Simple C++ DLL Loading a Message Box
  • Simple C++ Pointers and References

Related Articles

  • C++ Volatile Keyword
  • Perfect C++ String Explode Split
  • C/C++ Basic Structures of a Simple Program
  • Simple C++ Pointers and References
  • Inheritance, Polymorphism, and Virtual Functions

Programming Tutorials

Home

Singleton C++

Submitted by Baran Ornarli on Mon, 11/03/2008 - 20:28.
  • C++

Table of Contents

  1. C++ Singleton Example
  2. C++ Singleton Header File
  3. C++ Singleton File
  4. Major Flaw
  5. Flawed Solution
  6. Other Implementations for C++ Singleton

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
}
 
Log::~Log(){
  if(pInstance != 0)delete pInstance;
}

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.

Make sure you delete pInstance of course.

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!).


5
Average: 5 (1 vote)
»
  • Share Tutorial

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <img> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h4> <h2>
  • Lines and paragraphs break automatically.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".
  • You can use BBCode tags in the text. URLs will automatically be converted to links.
  • Table of contents based on the <h*> tags

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
                           .oooooo.       ooooooo  ooooo   o8o         .o8  
d8P' `Y8b `8888 d8' `"' "888
.oooo. oooo ooo 888 888 Y888..8P oooo .oooo888
`P )88b `88. .8' 888 888 `8888' `888 d88' `888
.oP"888 `88..8' 888 888 .8PY888. 888 888 888
d8( 888 `888' `88b d88b d8' `888b 888 888 888
`Y888""8o `8' `Y8bood8P'Ybd' o888o o88888o o888o `Y8bod88P"


Enter the code depicted in ASCII art style.

Navigation

  • Home
  • Forums
  • Image Gallery
  • Links
  • About
  • Contact

Why Register? Contribute articles and tutorials to ID, earn titles, learn from ID programming projects, and advertise your blog in our forums.

  • Forum Community
  • Register Now
  • Write an Article


Copyright © Inferno Development 2008-2009. All Rights Reserved.