January 25, 2008
Making Pimpl EasyPimpl at Work
Having been using the described Pimpl quite extensively lately, I could not help noticing that deploying other programming techniques was easy with the Pimpl. We have already talked about lazy data instantiation. Other examples might include deploying the Singleton:
// declaration
struct Foo : public pimpl<Foo>::pointer_semantics
{
// The public "constructor".
// Does not create new data but returns
// a reference to the singleton instance.
Foo();
private:
// Actual constructor.
Foo(parameters);
};
// implementation
Foo::Foo(): base(null())
{
static Foo single_foo(parameters);
*this = single_foo;
}
or managing/accessing a dictionary:
// In the implementation file
typedef std::map<string, Book> AllBooks;
static AllBooks books;
Book::Book(string const& title) : base(null())
{
AllBooks::iterator it = books.find(title);
// If the title found, return it.
// Otherwise, return an invalid book.
if (it != books.end()) *this = it->second;
}
or easy integration with boost::serialization and many other applications of the described Pimpl. Conclusion
Writing a conventional Pimpl-based class is not hard. However, repeating the same scaffolding over and over again is tedious and error-prone. Why do that if we do not have to? The suggested Pimpl generalization technique seems flexible, minimal and elegant, and helpful. It is yet another small gadget in your programming toolbox to make your work fun. Grab it, use it, tell me if there is anything missed and/or wrong and together we will get it even better. Acknowledgements
Many thanks to the people on the Boost developers mailing list for their constructive suggestions and especially to Peter Dimov for his incomplete-type management technique and the implementation of boost::impl_ptr ([10]) that I used the ideas for pimpl::impl_ptr from. References
1. Guru of the Week #24. http://www.gotw.ca/gotw/024.htm
|
|
||||||||||||||||||||||||||||||
|
|
|
|