Use pimpl to remove the implementation details from the header file.
-
By moving private member variables and private methods into the impl class, you can encapsulate data and methods to avoid declaring private methods in public header files.
-
Virtual methods cannot be hidden in the implementation class. Virtual methods must appear in the public class to be reloaded by the inheritance class.
-
You can add a pointer to the public class in the implementation class to facilitate the impl class to call the public method. Alternatively, you can pass the public class to the implementation class method that requires it.
-
Difference from Bridge pattern: the Bridge pattern is about object-oriented design, while the pimpl idiom is about physical design of files.
Explanation:
But in its basic and common form, a class using pimpl points to a single implementation, so there is no abstract class with distinct subclasses-just one class, forward declared, and compiled elsewhere. changing the implementation class does not require any recompilation of sources that include the main header.
For example, say you have a lot of private member functions, private enums, and private data. and these private "bits" change fairly frequently as the class is developed and maintained. if the # include dependencies are such that touching this header file causes a large number of sources to be recompiled, you have a good candidate for pimpl.
-
How to deploy pimpl: Making pimpl easy
-
Related books: large-scale C ++ Software Design
Autotimer. h
# Include <boost/shared_ptr.hpp>ClassAutotimer {Public:/// Create a new timer object with a human readable nameAutotimer (ConstSTD ::String& Name );/// On destruction, the timer reports how long it was alive~ Autotimer ();Private:// Make this object be noncopyable because it holds a pointerAutotimer (ConstAutotimer &);ConstAutotimer &Operator= (ConstAutotimer &);ClassImpl; Boost: shared_ptr <impl> mimpl ;};
Autotimer. cpp
# Include " Stdafx . H " # Include " Autotimer . H " # Include < Iostream > # Include < Windows . H > # Include < String >Class Autotimer :: Impl { Public : Double getelapsed () const {return (gettickcount ()-mstarttime)/1e3 ;} STD :: String Mname ; DWORD Mstarttime ;}; Autotimer :: Autotimer ( Const STD :: String & Name ): Mimpl ( New Autotimer :: Impl ()){ Mimpl- > Mname = Name ; Mimpl- > Mstarttime = gettickcount () ;} Autotimer ::~ Autotimer ( Void ){STD : : Cout <mimpl-> mname <": Took" <mimpl-> getelapsed () <"secs" <STD: Endl ;}
Main. cpp
# Include"Stdafx. h"# Include"Autotimer. h"# Include <iostream>Using NamespaceSTD;Int_ Tmain (IntArgc, _ tchar * argv []) {autotimer timer ("Mytimer");For(IntI = 0; I <10000; ++ I) {cout <".";}Cout <Endl;Return0 ;}