C++
  Home arrow C++ arrow Page 5 - C++ In Theory: The Singleton Pattern, Part...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

C++ In Theory: The Singleton Pattern, Part I
By: J. Nakamura
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 62
    2005-01-18

    Table of Contents:
  • C++ In Theory: The Singleton Pattern, Part I
  • A Logging Class
  • Statics are not Singletons
  • The Gamma Singleton
  • The Meyers Singleton

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    C++ In Theory: The Singleton Pattern, Part I - The Meyers Singleton


    (Page 5 of 5 )

    Luckily there is another solution that is very easy to implement and we call it the Meyers Singleton [Meyers]:

    class Log {
    public:
      static Log& Instance() {
        static Log theLog;
        return theLog;
    }
      void Write(char const *logline);
      bool SaveTo(char const *filename);
    private:
      Log();          // ctor is hidden
      Log(Log const&);      // copy ctor is hidden
      Log& operator=(Log const&);  // assign op is hidden

      static std::list<std::string> m_data;
    };

    This construction relies on the fact that function-static objects are only initialized when the function is first being called upon; thus we maintain the benefit of dynamic initialization. (Function-static primitive variables like static int number=100; do get translated during compile time however!)

    An additional safeguard is the returned reference instead of the pointer. The caller cannot be tempted to delete the singleton (as was the case when we were returning a pointer). The constructor is hidden, making it impossible for a user to instantiate a Log object; it would still be possible to assign the singleton Log to itself, however, and since this makes no sense we might just as well hide the assignment operator.

      Log::Instance().Write(“Test line”);  // works fine
      Log &myLog = Log::Instance();    // works fine
      Log another = myLog;  // FAILS
      myLog = myLog;    // works until we hide the assign ops!

    To wrap it all up, here is an abstract of the Meyers Singleton:

    class Singleton {
    public:
    static Singleton& Instance() {
      static Singleton theSingleton;
      return theSingleton;
    }
    /* more (non-static) functions here */
    private:
    Singleton(); // ctor hidden
    Singleton(Singleton const&); // copy ctor hidden
    Singleton& operator=(Singleton const&); // assign op. hidden
    ~Singleton(); // dtor hidden
    };

    In the next article in this series, we will look at how to generalize this class, and at the construction/destruction sequencing problems.

    REFERENCES

    [Gamma] Design Patterns: E.Gamma, R.Helm, R.Johnson and J.Vlissides.
    [Meyers] More Effective C++: S.Meyers.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The article isw very good for a beginner showing him how the solution...
       · class LogNetwork : public LogNetwork {};I don't think this is right.a class...
       · You are very right it should beclass LogNetwork : public LogBasethx for...
       · "...which can be written to a single file when Log::Write is called."That should...
       · You discussed using polymorphism to have different logging behaviors, and using the...
     

    C++ ARTICLES

    - More Tricks to Gain Speed in Programming Con...
    - Easy and Efficient Programming for Contests
    - Preparing For Programming Contests
    - Programming Contests: Why Bother?
    - Polymorphism in C++
    - Overview of Virtual Functions
    - Inheritance in C++
    - Extending the Basic Streams in C++
    - Using Stringstreams in C++
    - Custom Stream Manipulation in C++
    - General Stream Manipulation in C++
    - Serialize Your Class into Streams in C++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT