Stack based "pimpl"
Hi! I'd like to implement a pimpl, pointing to a stack "allocated" buffer by means of palcement new/destroy. There would be no problem but there are alignment issues. What really I need is: - a way to check by te means of Boost wheater that an object of class X can be placed (with placement new) in a buffer of given adress and size: - a way of getting a pointer to X (within the buffer) where the object could be paced // file.hpp: struct X { X(); ~X(); private: struct Impl; const static int max_size = 100; Impl* m_pimpl; char m_impl_buffer[max_size]; bool m_on_stack; }; // file.cpp: #include "file.hpp" struct X::Impl { // members }; X::X() { m_on_stack = value_of(max_size is big enough for an object of X); if (m_on_stack) m_pimpl = new (m_impl_buffer)Impl; // any alignment stuff here??? else m_pimpl = new Impl; } X::~X() { if (m_on_stack) m_pimpl->~Impl(); else delete m_pimpl; } I'll be gratefull for any help, Michal
On Aug 5, 2005, at 2:07 PM, Michal Kandulski wrote:
Hi!
I'd like to implement a pimpl, pointing to a stack "allocated" buffer by means of palcement new/destroy.
There would be no problem but there are alignment issues.
What really I need is: - a way to check by te means of Boost wheater that an object of class X can be placed (with placement new) in a buffer of given adress and size: - a way of getting a pointer to X (within the buffer) where the object could be paced
boost::optional<T> does this, as does the more-complicated boost::variant. You'll want to use the type traits alignment_of (to find the alignment of a type) and type_with_alignment (to find a POD type with a given alignment). If you dig around Boost for aligned_storage you'll see the technique we've used. Doug
Douglas Gregor wrote:
On Aug 5, 2005, at 2:07 PM, Michal Kandulski wrote:
Hi!
I'd like to implement a pimpl, pointing to a stack "allocated" buffer by means of palcement new/destroy.
There would be no problem but there are alignment issues.
What really I need is: - a way to check by te means of Boost wheater that an object of class X can be placed (with placement new) in a buffer of given adress and size: - a way of getting a pointer to X (within the buffer) where the object could be paced
boost::optional<T> does this, as does the more-complicated boost::variant.
You'll want to use the type traits alignment_of (to find the alignment of a type) and type_with_alignment (to find a POD type with a given alignment). If you dig around Boost for aligned_storage you'll see the technique we've used.
Doug
Thanks for the answer, but I've already checked both optional and variant.
OK. I can get a POD type suitable to store an object of X, but
my problem is: how to determine whether the object can be stored in
a given stack "allocated" buffer of given size.
My input data is:
- alignment_of<X>::value,
- sizeof(X),
- (aligned_storage
participants (2)
-
Douglas Gregor
-
Michal Kandulski