2

Pimplイディオムをローカルストレージイディオムに適用したい:


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();
}

このアプローチで私が抱えている唯一の懸念は、の調整ですm_storagecharintと同じように整列されるとは限りません。アトミックには、さらに制限の厳しい配置要件があります。アライメント値を定義(およびアサート)する機能を提供するストレージを宣言するためのchar配列よりも優れたものを探しています。何か知っていますか?多分ブーストライブラリはすでにこれを行っていますか?

4

3 に答える 3

4

boost::aligned_storage http://www.boost.org/doc/libs/1_43_0/libs/type_traits/doc/html/boost_typetraits/reference/aligned_storage.htmlでうまくいくはずです。

ただし、通常のpimplアプローチを使用していない理由はありますか?

于 2011-10-28T15:58:59.723 に答える
3

を見てくださいboost::aligned_storage。使用法は非常に簡単です:

#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));
于 2011-10-28T16:00:19.113 に答える
3

ここでの通常の解決策は、システム上で最も多くのアライメントを必要とするタイプ(通常はdouble)のユニオンを使用することです。

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

使用するタイプがわからない場合は、すべての基本タイプに加えて、いくつかのポインター(データ、void、関数)を入れてください。

于 2011-10-28T16:08:35.830 に答える