Two ways to implement a single case pattern

Source: Internet
Author: User

1. A Hungry man mode:

#include <iostream>
using namespace std;
Class Singleton {public
:
	static singleton& getinst (void) {return
		s_inst;
	}
Private:
	Singleton (void) {}
	Singleton (const singleton&);
	Static Singleton s_inst;
Singleton Singleton::s_inst;
int main (void) {
	singleton& S1 = Singleton::getinst ();
	singleton& s2 = Singleton::getinst ();
	singleton& s3 = Singleton::getinst ();
	cout << &s1 << ' << &s2 << ' << &s3 << Endl;
	return 0;
}


2. Lazy mode

#include <iostream>
using namespace std;
Class Singleton {public
:
	static singleton& getinst (void) {
		if (! M_inst)
			m_inst = new Singleton;
  ++M_CN;
		return *m_inst;
	}
	void Releaseinst (void) {
		if (m_cn &&--m_cn = 0)
			delete this;
	}
Private:
	Singleton (void) {
		cout << "constructed:" << this << Endl;
	}
	Singleton (const singleton&);
	~singleton (void) {
		cout << "destructor:" << this << Endl;
		M_inst = NULL;
	}
	Static singleton* M_inst;
	static unsigned int m_cn;
singleton* singleton::m_inst = NULL;
unsigned int singleton::m_cn = 0;
int main (void) {
	singleton& S1 = Singleton::getinst ();
	singleton& s2 = Singleton::getinst ();
	singleton& s3 = Singleton::getinst ();
	cout << &s1 << ' << &s2 << ' << &s3 << Endl;
	S3.releaseinst ();
	S2.releaseinst ();
	S1.releaseinst ();
	return 0;
}

The difference between two modes: there is only one static variable in the lazy mode, one variable that is returned once by the Getinst function. Lazy mode inside the maintenance of a static pointer variable and a static variable to do the counter, each time the tune will first judge if there is no construction, if the construction of M_inst is not empty, the counter directly + + is good, call the destructor is to judge the counter, no one used to release this memory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.