我想與本地存儲的成語適用PIMPL方法:便攜式C++對齊?
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_storage
的對齊方式。不保證與int應該以相同的方式對齊。原子能可能有更嚴格的對準要求。我正在尋找比char數組更好的東西來聲明存儲,這使我能夠定義(並斷言)對齊值。你知道這種事嗎?也許增強圖書館已經做到了這一點?
這將不會編譯。數組變量具有名稱右側的大小:'char m_storage [storage];'。 –
謝謝,已經修復了它 – lurscher