c_cpp 单例类实现

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 单例类实现相关的知识,希望对你有一定的参考价值。

class singleton {
private:
	static singleton* pInstance = NULL;   // gist, need initialization
public:
	// good for single-thread usage
	singleton* getInstance() {
		if(pInstance == NULL)
			pInstance = new singleton;
		return pInstance;
	}

	// DCLP method: Double-checked lock pattern
	// Good for multi-threaded usage
	// http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
	singleton* getInstance2() {
		if(pInstance == 0) {
			Lock lock;
			if(pInstance == 0) {
				pInstance = new singleton;
			}
		}
		return pInstance;
	}
};

// http://stackoverflow.com/questions/86582/singleton-how-should-it-be-used
// read Chapter 3.2.1 in Book <API design for C++> for details and why.

class singleton {
private:
  // declare constructor and descructor to private to prevent creating subclass.
	singleton();
	~singleton(); // prevent client from deleting the instance
	// stop compiler generating methods of copy object
	singleton(const singleton& copy); // not implemented
	singleton& operator=(const singleton& copy); // not implemented
public:
  // Returning pointer or reference are both fine. But return reference is prefered.
  // because if return pointer, clients could potentially delete the instance.
	static singleton& getInstance3() {
		// the only instance, guranteed to be lazy initialized
		// guranteed that it will be destroyed correctly
		// however, below is not thread-safe.
		static singleton instance;
		return instance;
	}
};

// the most concise version
class S {
private:
	S();
	~S();
	S(const S& c);
	S& operator=(const S& c);
public:
	static S& getInstance3() {
		static S instance;
		return instance;
	}
};

以上是关于c_cpp 单例类实现的主要内容,如果未能解决你的问题,请参考以下文章

单例类

双重检查锁实现单例(java)

单例模式

如何快速创建单例类? [复制]

单例模式

java单例类的几种实现