Use the right alignment for a buffer which is supposed to hold a struct in C++ -
suppose have struct, say
struct s { double a, b; ~s(); // s doesn't have pod };
such struct should typically have alignment of 8, size of largest contained type 8.
now imagine want declare placeholder struct hold value of s
:
struct placeholder { char bytes[ sizeof( s ) ]; };
now want place inside of class:
class user { char somechar; placeholder holder; public: // don't mind hacky -- shows possible use // that's not point of question user() { new ( holder.bytes ) s; } ~user() { ( ( s * )( holder.bytes ) )->~s(); } };
problem is, placeholder
aligned incorrectly within user
. since compiler knows placeholder
made of chars, not doubles, typically use alignment of 1.
is there way declare placeholder
alignment matching of s
in c++03? note s
not pod type. understand c++11 has alignas
, not universally available yet, i'd rather not count on if possible.
update: clarify, should work s
- don't know contains.
i believe boost::aligned_storage
may you're looking for. uses union trick in such way type doesn't matter (you use sizeof(yourtype)
tell how align) make sure alignment works out properly.
Comments
Post a Comment