Re: Pimpl idiom without dynamic memory allocation
Daniel Lidström wrote:
> I have just discovered a way to use the private implementation idiom
> (pimpl), without the overhead of dynamic memory allocation.
[ storing a reference to a temporary ]
As you noticed, this doesn't work. However, there is a method that works.
All you have to do is to add a suitably aligned and sufficiently large
buffer into the class:
class foo {
aligned_storage<42> m_impl;
class implementation;
foo();
~foo();
void some_function();
};
class foo::implementation { ... };
foo::foo() {
// placement new
new m_impl.get<void>() implementation;
}
foo::~foo() {
// explicit dtor invokation
m_impl.get<implementation>()->~implementation;
}
void foo::some_function() {
m_impl.get<implementation>()->some_function();
}
Is it worth the hassle? Typically not, in particular since it's hard to
guarantee that you have both enough but still not too much memory.
Uli
|