The pImpl (pointer to implementation) idiom is a popular design pattern in C++ used to encapsulate implementation details and reduce compile-time dependencies. It allows for a separation between the interface and implementation which can be beneficial for hiding complex implementations and enhancing build times.
#include <iostream>
// Forward declaration of the implementation class
class WidgetImpl;
// Interface class
class Widget {
public:
Widget();
~Widget();
void doSomething();
private:
WidgetImpl* pImpl; // Pointer to implementation
};
// Implementation class
class WidgetImpl {
public:
void doSomething() {
std::cout << "Doing something!" << std::endl;
}
};
// Constructor: allocate the implementation
Widget::Widget() : pImpl(new WidgetImpl) {}
// Destructor: clean up the implementation
Widget::~Widget() {
delete pImpl;
}
// Forwarding function to implementation
void Widget::doSomething() {
pImpl->doSomething();
}
int main() {
Widget widget;
widget.doSomething();
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?