portable c++ alignment?

1k Views Asked by At

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?

3

There are 3 best solutions below

7
On BEST ANSWER

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?

0
On

Take a look at boost::aligned_storage. The usage is pretty simple:

#include <boost/aligned_storage.hpp>
#include <boost/type_traits/alignment_of.hpp>


typedef boost::aligned_storage<sizeof(ptime), boost::alignment_of<ptime>::value> storage_type;

using boost::posix_time::ptime;
storage_type unix_epoch_storage_;

new (unix_epoch_storage_.address()) ptime(date(1970, 1, 1));
2
On

The usual solution here is to use a union with the type requiring the most alignment on your system (typically a double):

static int const requiredStorage = 20;
union
{
    unsigned char myStorage[requiredStorage];
    double dummyForAlignment;
};

If you're unsure of which type to use, just throw in all of the basic types, plus a few pointers (to data, to void, to a function) to be sure.