Skip to content

Instantly share code, notes, and snippets.

@wyw
Forked from cloudwu/pimpl.cpp
Created June 14, 2017 11:08
Show Gist options
  • Save wyw/e39ec21fae300f3f36a57ee1f3002cde to your computer and use it in GitHub Desktop.
Save wyw/e39ec21fae300f3f36a57ee1f3002cde to your computer and use it in GitHub Desktop.
My version of pimpl
// My version of pimpl ([email protected])
// See http://en.cppreference.com/w/cpp/language/pimpl
#include <iostream>
// interface (widget.h)
class widget {
struct impl;
public:
static widget* create(int); // replacement of new
void release() const; // replacement of delete
void draw() const; // public API that will be forwarded to the implementation
void draw();
bool shown() const { return true; } // public API that implementation has to call
};
// implementation (widget.cpp)
#define DESC_SELF impl * self = static_cast<impl *>(this);
#define CONST_SELF const impl * self = static_cast<const impl *>(this);
struct widget::impl : widget {
int n; // private data
impl(int n) : n(n) {}
};
widget * widget::create(int n) {
return new impl(n);
}
void widget::release() const {
CONST_SELF
delete self;
}
void widget::draw() const {
CONST_SELF
if(self->shown()) { // this call to public member function requires the back-reference
std::cout << "drawing a const widget " << self->n << '\n';
}
}
void widget::draw() {
DESC_SELF
if(self->shown()) {
std::cout << "drawing a non-const widget " << self->n << '\n';
}
}
// user (main.cpp)
int main()
{
widget *w = widget::create(7);
const widget *w2 = widget::create(8);
w->draw();
w2->draw();
w->release();
w2->release();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment