40
votes

I write a singleton c++ in the follow way:

class A {
    private:
        static A* m_pA;
        A();
        virtual ~A();

    public:
        static A* GetInstance();
        static void FreeInstance();

        void WORK1();
        void WORK2();
        void WORK3();
    }
}

A* A::GetInstance() {
    if (m_pA == NULL)
        m_pA = new A();
    return m_pA;
}

A::~A() {
    FreeInstance()  // Can I write this? are there any potential error?
}

void A::FreeInstance() {
    delete m_pA;
    m_pA = NULL;
}

Thanks! Evan Teran and sep61.myopenid.com 's answer is right, and really good! My way is wrong, I wish any one writting such code can avoid my silly mistake.

My singleton A in my project has a vector of smart pointer, and another thread can also edit this vector, so when the application is closing, it always become unstable even I add lots of CMutex. Multithread error + singleton error wasted me 1 day.

//----------------------------------------------------------- A new singleton, you are welcome to edit if you think there is any problem in the following sample:

class A {
    private:
        static A* m_pA;
        explicit A();
        void A(const A& a);
        void A(A &a);
        const A& operator=(const A& a);
        virtual ~A();

    public:
        static A* GetInstance();
        static void FreeInstance();

        void WORK1();
        void WORK2();
        void WORK3();
    }
}

A* A::GetInstance() {
    if (m_pA == NULL){
        static A self;
        m_pA = &self;
    }
    return m_pA;
}

A::~A() {
}
10
An interesting discussion on how to properly implement a singleton, along with thread-safety in C++ can be found in this paper: aristeia.com/Papers/DDJ%5FJul%5FAug%5F2004%5Frevised.pdfMatthieu N.
Possible duplicate of C++ Singleton design pattern. The stackoverflow.com/q/1008019/52074 is better because it 10x more upvotes and the question is more up-to-date with C++11 AND the question/answer is being protected/maintained by the community.Trevor Boyd Smith

10 Answers

205
votes

Why does everybody want to return a singleton as a pointer?
Return it as a reference seems much more logical!

You should never be able to free a singleton manually. How do you know who is keeping a reference to the singleton? If you don't know (or can't guarantee) nobody has a reference (in your case via a pointer) then you have no business freeing the object.

Use the static in a function method.
This guarantees that it is created and destroyed only once. It also gives you lazy initialization for free.

class S
{
    public:
        static S& getInstance()
        {
            static S    instance;
            return instance;
        }
    private:
        S() {}
        S(S const&);              // Don't Implement.
        void operator=(S const&); // Don't implement
 };

Note you also need to make the constructor private. Also make sure that you override the default copy constructor and assignment operator so that you can not make a copy of the singleton (otherwise it would not be a singleton).

Also read:

To make sure you are using a singleton for the correct reasons.

Though technically not thread safe in the general case see:
What is the lifetime of a static variable in a C++ function?

GCC has an explicit patch to compensate for this:
http://gcc.gnu.org/ml/gcc-patches/2004-09/msg00265.html

13
votes

You can avoid needing to delete it by using a static object like this:

if(m_pA == 0) {
    static A static_instance;
    m_pA = &static_instance;
}
4
votes

A singleton in C++ can be written in this way:

static A* A::GetInstance() {
    static A sin;
    return &sin;
}
3
votes

Just don't forget to make the copy constructor and assignment operators private.

1
votes

I do not think there is any reason to write that line no. Your destructor method is not static and your singleton instance will not be destructed in that fashion. I do not think the destructor is necessary, if you need to cleanup the object use the static method you've alread created, FreeInstance().

Other than that, you create your singletons in roughly the same way that I create mine.

1
votes

After a period of wild enthusiasm for Meyers-style singletons (using local static objects as in some of the previous answers), I got completely sick of the lifetime management problems in complicated apps.

I tend to find that you end up referencing the 'Instance' method deliberately early in the app's initialisation, to make sure they're created when you want, and then playing all kinds of games with the tear-down because of the unpredictable (or at least very complicated and somewhat hidden) order in which things get destroyed.

YMMV of course, and it depends a bit on the nature of the singleton itself, but a lot of the waffle about clever singletons (and the threading/locking issues which surround the cleverness) is overrated IMO.

1
votes

if you read "Modern C++ Design" you'll realize that a singleton design could be much complex than return a static variable.

0
votes

This implementation is fine as long as you can answer these questions:

  1. do you know when the object will be created (if you use a static object instead of new? Do you have a main()?)

  2. does you singleton have any dependencies that may not be ready by the time it is created? If you use a static object instead of new, what libraries have been initialized by this time? What your object does in constructor that might require them?

  3. when will it be deleted?

Using new() is safer because you control where and when the object will be created and deleted. But then you need to delete it explicitly and probably nobody in the system knows when to do so. You may use atexit() for that, if it makes sense.

Using a static object in method means that do do not really know when it will be created or deleted. You could as well use a global static object in a namespace and avoid getInstance() at all - it doesn't add much.

If you do use threads, then you're in big trouble. It is virtually impossible to create usable thread safe singleton in C++ due to:

  1. permanent lock in getInstance is very heavy - a full context switch at every getInstance()
  2. double checked lock fails due to compiler optimizations and cache/weak memory model, is very tricky to implement, and impossible to test. I wouldn't attempt to do it in a real system, unless you intimately know your architecture and want it to be not portable

These can be Googled easily, but here's a good link on weak memory model: http://ridiculousfish.com/blog/archives/2007/02/17/barrier.

One solution would be to use locking but require that users cache the pointer they get from getInctance() and be prepared for getInstance() to be heavy.

Another solution would be to let users handle thread safety themselves.

Yet another solution would be to use a function with simple locking and substitute it with another function without locking and checking once the new() has been called. This works, but full implementation is complicated.

0
votes

There is a great C++ library, ACE, based on patterns. There's a lot of documentation about different kind of patterns so look at their work: http://www.cs.wustl.edu/~schmidt/ACE.html

0
votes
//! @file singleton.h
//!
//! @brief Variadic template to make a singleton out of an ordinary type.
//!
//! This template makes a singleton out of a type without a default
//! constructor.

#ifndef SINGLETON_H
#define SINGLETON_H

#include <stdexcept>

template <typename C, typename ...Args>
class singleton
{
private:
  singleton() = default;
  static C* m_instance;

public:
  singleton(const singleton&) = delete;
  singleton& operator=(const singleton&) = delete;
  singleton(singleton&&) = delete;
  singleton& operator=(singleton&&) = delete;

  ~singleton()
  {
    delete m_instance;
    m_instance = nullptr;
  }

  static C& create(Args...args)
  {
    if (m_instance != nullptr)
      {
    delete m_instance;
    m_instance = nullptr;
      }
    m_instance = new C(args...);
    return *m_instance;
  }

  static C& instance()
  {
    if (m_instance == nullptr)
      throw std::logic_error(
        "singleton<>::create(...) must precede singleton<>::instance()");
    return *m_instance;
  }
};

template <typename C, typename ...Args>
C* singleton<C, Args...>::m_instance = nullptr;

#endif // SINGLETON_H