Noncopyable in boost
Keywords: noncopyable;
Note: I studied the source code of the mangos server today and found a skilled noncopyable class.
Looking at boost code today, we found that many classes inherit noncopyable. below is the code for noncopyable:
Class noncopyable
{
Protected:
Noncopyable (){}
~ Noncopyable (){}
PRIVATE: // emphasize the following members are private
Noncopyable (const noncopyable &);
Const noncopyable & operator = (const noncopyable &);
};
The design concept here is to let the subclass inherit, but to prevent the subclass from calling the assignment and copy constructor, what is the purpose?
When writing code, I often like to use Singleton mode, such as factory and manager classes, but write
In Singleton, we certainly hope that there is only one global one, and we do not want others to create one when they use it.
Every time a singleton class is written, the constructor, value assignment function, destructor, and copy constructor must be hidden in the declaration of the class.
Private or protected. This is really tiring.
Now, just let these Singleton inherit noncopyable directly. In this way, at least assign values and copy structures are not required.
The function is ready. The constructor and destructor depend on the situation.
The basic idea of class noncopyable is to set the protected permission for constructor and destructor so that the subclass can be called, but the external class cannot be called,
So when the subclass needs to define the constructor, the compilation will not fail. But the most important thing is that noncopyable makes the copy constructor and the copy assignment function
Private, which means that, unless the subclass defines its own copy constructor and value assignment function, the external caller cannot pass
Assign values and copy structures to generate a new subclass object. A simple example:
Class test: Public noncopyable
{
};
Void main ()
{
Test A, C;
Test B (a); // <------ (1) Error
C = A; // <------ (2) Error
}
If the test class does not inherit noncopyable, both (1) and (2) can be compiled. However, once test inherits noncopyable, both (1) and (2) fail.
Compilation can prevent the caller from writing some wrong code. Isn't this exactly what we need to do with the singleton object?