I want to apply the Pimpl idiom with local storage idiom:
mytype.h
class mytype {
struct Impl;
enum{ storage = 20; }
char m_storage[ storage ];
Impl* PImpl() { return (Impl*)m_storage; }
public:
mytype();
~mytype();
void myMethod();
};
mytype.cpp
#include "mytype.h"
struct mytype::Impl {
int foo;
void doMethod() { foo = (foo-1)*3; };
}
mytype::mytype() {
new (PImpl()) Impl(); // placement new
//check this at compile-time
static_assert( sizeof(Impl) == mytype::storage );
//assert alignment?
}
mytype::~mytype() {
PImpl()->~();
}
void mytype::myMethod() {
PImpl()->doMethod();
}
the only concern i have with this approach is alignment of m_storage
. char
is not guaranteed to be aligned in the same way as an int should be. Atomics could have even more restrictive alignment requirements. I'm looking for something better than a char array to declare storage that gives me the ability to also define (and assert) alignment values. Do you know anything of the sort? maybe a boost library already does this?
boost::aligned_storage
http://www.boost.org/doc/libs/1_43_0/libs/type_traits/doc/html/boost_typetraits/reference/aligned_storage.html should do the trick.
Is there a reason you aren't just using the normal pimpl approach though?