A single-header C++ library for PIMPLs without having to implement any special member functions as described in oliora's blog.
Header File:
#include"spimpl.h"classCopyable {
public:Copyable(int x);
intx();
// All five special members are compiler-generated.private:classImpl;
// Movable and copyable Smart PIMPL
spimpl::impl_ptr<Impl> impl_;
};Implementation File:
Copyable::Copyable(int x)
: impl_(spimpl::make_impl<Impl>(x)) {}
structCopyable::Impl {
Impl(int x): x(x) {}
int x;
};
intCopyable::x() {
return impl_->x;
}For easier debugging with GDB you might want to add the following to your
.gdbinit file. This makes *impl_ and impl-> behave more naturally in
GDB.
pythonimportgdbimportgdb.xmethodimportlibstdcxx.v6.xmethodsfromlibstdcxx.v6importregister_libstdcxx_printersregister_libstdcxx_printers (None)
classSpimplGetWorker(gdb.xmethod.XMethodWorker):
def__init__(self, elem_type): self.elem_type=elem_typedefget_arg_types(self): returnNonedefget_result_type(self, obj): returnself.elem_type.pointer()
def__call__(self, obj):
ptr=obj['ptr_']
eval_string='(*(%s*)(%s)).get()'%(ptr.type, ptr.address)
returngdb.parse_and_eval(eval_string)
classSpimplDerefWorker(SpimplGetWorker):
def__init__(self, elem_type): SpimplGetWorker.__init__(self, elem_type)
defget_arg_types(self): returnNonedefget_result_type(self, obj): returnself.elem_typedef__call__(self, obj):
returnSpimplGetWorker.__call__(self, obj).dereference()
classSpimplMethodsMatcher(gdb.xmethod.XMethodMatcher):
def__init__(self):
gdb.xmethod.XMethodMatcher.__init__(self, 'spimpl')
self._method_dict= {
'operator->': libstdcxx.v6.xmethods.LibStdCxxXMethod('operator->', SpimplGetWorker),
'operator*': libstdcxx.v6.xmethods.LibStdCxxXMethod('operator*', SpimplDerefWorker),
}
self.methods= [self._method_dict[m] forminself._method_dict]
defmatch(self, class_type, method_name):
ifnotre.match('^spimpl::impl_ptr<.*>$', class_type.tag):
returnNonemethod=self._method_dict.get(method_name)
ifmethodisNoneornotmethod.enabled:
returnNonereturnmethod.worker_class(class_type.template_argument(0))
gdb.xmethod.register_xmethod_matcher(None, SpimplMethodsMatcher())
end