Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

portable c++ alignment?

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?

like image 405
lurscher Avatar asked Dec 31 '25 14:12

lurscher


2 Answers

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?

like image 119
Mark B Avatar answered Jan 02 '26 04:01

Mark B


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));
like image 45
Nathan Ernst Avatar answered Jan 02 '26 03:01

Nathan Ernst