Recently a friend asked me to create a single instance of a problem, he wrote a C + + Single-instance class Csingleton, and its constructors are private types. This class has a static function: GetInstance, which returns a reference to a singleton class object, which can restrict the replication of an object by declaring the instance with this function:// 这一句编译器通不过
CSingleton temp = CSingleton::GetInstance();
However, the compiler is always blocked at the top of this line of code. What the hell is this about?
In fact, the problem can be solved simply by figuring out some details of the compiler's handling of single-instance classes. When the compiler touches the above statement, it looks for the copy constructor of the class, the so-called copy constructor, which is a constructor named Csingleton (const csingleton&). If you do not provide this copy constructor, then the C + + compiler will provide you with a default copy constructor. What this default copy constructor does is simple, simply by leaning the byte from one object to another. If you want this copy constructor to do something else, you have to implement your own copy constructor. To limit the replication of objects, you must also make this copy constructor private:
class CSingleton {
private:
// 私有类型的拷贝构造函数
CSingleton(const CSingleton& obj)
{ ASSERT(FALSE); } // should never happen
};
In addition, you must implement the default constructor, which is a constructor without parameters, and if there is no default constructor, you will not be able to create an object instance. The default constructor can be either private or protected, which depends on whether you want to derive other classes from Csingleton. To sum up, to create a single instance class correctly, the following guidelines or tips are helpful:
Create default constructors, copy constructors, and assignment operators, and their types are private types.
Creates a static function getinstance that returns a unique object instance
The following is a specific example code:
//If you compile this program, an error is generated. See comments for main function
//
class Csingleton {
Public:
Static csingleton& getinstance () {
Static Csingleto n Theinstance; Unique instance
return theinstance;
Protected:
//requires the default constructor ctor
//Because to create a derived class, ctor is protected type
Csingleton () {}
Private:
CS Ingleton (const csingleton& o) {}
csingleton& operator= (const csingleton& o) {}
};
void Main () br> {
//Because constructors are private types, these lines are not compiled:
Csingleton x = csingleton::getinstance ();//Error:private
Copy ctor!
Csingleton y = csingleton::getinstance ();//Error:private
//Copy ctor!
x = y; Error:private
//assignment!
The compiler will be more satisfied with this instance declaration:
Csingleton *p1 = Csingleton::getinstance ();
Csingleton *p2 = P1->getinstance ();
Csingleton & ref = * Csingleton::getinstance ();
}
This article supporting source code