The reason to declare a constructor as protected is simple, but the reason why the constructor is declared private is seldom known. Syntactically speaking, if any function is declared as private, this function cannot be called from outside, the constructor is also a function, on the contrary, can only be used in the internal constructor, but some scenarios are to do so, to achieve a certain degree of programming effect: 1. Shield constructor, is not to let you create the object of this class, just do not want you to be outside the other functions directly new to the class, and can only be constructed from within this class (such as the following code). 2. Prevent other functions from executing copy constructors or assignment operators in this class, avoid the compiler automatically generating default copy constructors, do not want to follow the default copy constructor for verbatim copy or assignment operators, you can declare a copy constructor or assignment operator as private
1 classIOCP2 {3 Private:4 IOCP ()5 {6 //Create a completion port (note: A queue that the OS maintains, and the OS puts a handle to the event notification that the I/O operation has completed)7 if((M_HIOCP = CreateIoCompletionPort (INVALID_HANDLE_VALUE, NULL, NULL,0)) ==NULL)8 ;9 //creates a worker thread to handle the completion of a port message.TenM_hworkerthread = CreateThread (NULL,0, Workthread, (LPVOID) This,0, &M_workerthreadid); One }; A~IOCP (); - Private: - Staticiocp*m_instance; the Public: - Staticiocp*Instance () - { - if(M_instance = =NULL) + { -M_instance =NewIOCP (); + } A returnm_instance; at } - voidWait (); - StaticDWORD __stdcall Workthread (LPVOID Param); -HANDLE M_HIOCP;//handle to completion port - Private: -HANDLE M_hworkerthread;//worker thread handle in DWORD M_workerthreadid; - Public: to //bind a socket to the completion port + BOOLRegistertocompletionport (Socket socket,void*completionkey); -};
An example of a real C + + singleton pattern