c++ - How would I portably implement aligned stack storage in C++03? -
in c++03 code, how portably implement unsigned char[sizeof(t)]
buffer has same size , alignment of given type t
?
for example:
template<class t> void test() { unsigned char buffer[sizeof(t)]; // <----- how ensure aligned? if (some_condition()) { t *const obj = new(buffer) t(); // ... obj->~t(); } else { /* use 'buffer' else */ } }
is possible, or forced use compiler extensions in order implement this?
in guru of week #28 column, herb sutter uses union it's less robust boost's efforts.
boost's aligned_storage solves gory details you. if @ implementation, you'll see uses mscv's __alignof
or gcc's __alignof__
template: type_with_alignment
.
from own codebase, once used (derived gotw link above):
#if defined(_msc_full_ver) && (_msc_full_ver >= 150020706) # pragma warning(push) # pragma warning(disable: 4371) #endif // #if (defined(_msc_full_ver) && (_msc_full_ver >= 150020706) union alignedstorage { char storage[sizeof(t)]; int16 dummy0; int32 dummy1; int64 dummy2; float dummy3; double dummy4; long double dummy5; void (*dummy6)(); struct dummy7; int dummy7::*dummy8; #if defined(_msc_full_ver) && (_msc_full_ver >= 140050215) # pragma warning(push) # pragma warning(disable: 4121) #endif // #if (defined(_msc_full_ver) && (_msc_full_ver >= 140050215) int (dummy7::*dummy9)(int); #if defined(_msc_full_ver) && (_msc_full_ver >= 140050215) # pragma warning(pop) #endif // #if (defined(_msc_full_ver) && (_msc_full_ver >= 140050215) }; // alignedstorage #if defined(_msc_full_ver) && (_msc_full_ver >= 150020706) # pragma warning(pop) #endif // #if (defined(_msc_full_ver) && (_msc_full_ver >= 150020706)
these days rely on boost since covers many more corner cases , compiler specificities
Comments
Post a Comment