Benefits of the "PIMPL" Idiom
In the "Pointer to Implementation" (PIMPL) idiom, a public class encapsulates an internal structure or class (the "implementation"), providing implementation hiding from external users. This technique offers several advantages:
Design Considerations for "Pimpl Class"
While PIMPL isolates implementation, placing public methods on the PIMPL class instead of the public class may seem counterintuitive. However, this approach ensures that:
Example Implementation with Isolated Implementation
Consider the example code below, where the "Purr()" implementation is contained within the PIMPL class:
// header file: class Cat { private: class CatImpl; // PIMPL class CatImpl* cat_; // Pointer to PIMPL public: Cat(); // Constructor ~Cat(); // Destructor Purr(); // Public method }; // CPP file: #include "cat.h" class Cat::CatImpl { public: Purr(); }; Cat::Cat() { cat_ = new CatImpl; } Cat::~Cat() { delete cat_; } void Cat::Purr() { cat_->Purr(); } void CatImpl::Purr() { // Actual implementation of "Purr()" }
In this example, the public class "Cat" handles the creation and destruction of the "CatImpl" object but delegates the implementation of "Purr()" to the PIMPL class. This approach ensures that the details of the "Purr()" implementation are hidden from external users while providing a stable interface for interacting with the "Cat" class.
The above is the detailed content of What are the benefits and considerations of using the PIMPL idiom in C ?. For more information, please follow other related articles on the PHP Chinese website!