// file x.h
struct X {
int data;
};
// file y.h
#include <cstddef>
#include <type_traits>
class Y {
public:
Y();
~Y();
/*...*/
private:
static const size_t sizeofx = 8;
static const size_t alignofx = 4;
std::aligned_storage<sizeofx, alignofx>::type _x;
};
// file y.cpp
#include <new>
//#include "y.h"
//#include "x.h"
Y::Y() {
// compile-time checks
static_assert(sizeofx >= sizeof(X), "sizeofx too small");
static_assert(alignofx == alignof(X), "alignofx is incorrect");
// does not allocate memory, but constructs an object at &_x
new (&_x) X;
}
Y::~Y() {
(reinterpret_cast<X*>(&_x))->~X();
}
// file main.cpp
//#include "y.h"
int main()
{
Y y;
return 0;
}
Ly8gZmlsZSB4LmgKc3RydWN0IFggewogIGludCBkYXRhOwp9OwoKCi8vIGZpbGUgeS5oCiNpbmNsdWRlIDxjc3RkZGVmPgojaW5jbHVkZSA8dHlwZV90cmFpdHM+CgpjbGFzcyBZIHsKcHVibGljOgogIFkoKTsKICB+WSgpOwogIC8qLi4uKi8KcHJpdmF0ZToKICBzdGF0aWMgY29uc3Qgc2l6ZV90IHNpemVvZnggPSA4OwogIHN0YXRpYyBjb25zdCBzaXplX3QgYWxpZ25vZnggPSA0OwoKICBzdGQ6OmFsaWduZWRfc3RvcmFnZTxzaXplb2Z4LCBhbGlnbm9meD46OnR5cGUgX3g7Cn07CgovLyBmaWxlIHkuY3BwCiNpbmNsdWRlIDxuZXc+Ci8vI2luY2x1ZGUgInkuaCIKLy8jaW5jbHVkZSAieC5oIgoKWTo6WSgpIHsKICAvLyBjb21waWxlLXRpbWUgY2hlY2tzCiAgc3RhdGljX2Fzc2VydChzaXplb2Z4ICA+PSBzaXplb2YoWCksICAic2l6ZW9meCB0b28gc21hbGwiKTsKICBzdGF0aWNfYXNzZXJ0KGFsaWdub2Z4ID09IGFsaWdub2YoWCksICJhbGlnbm9meCBpcyBpbmNvcnJlY3QiKTsKICAvLyBkb2VzIG5vdCBhbGxvY2F0ZSBtZW1vcnksIGJ1dCBjb25zdHJ1Y3RzIGFuIG9iamVjdCBhdCAmX3gKICBuZXcgKCZfeCkgWDsKfQoKWTo6flkoKSB7CiAgKHJlaW50ZXJwcmV0X2Nhc3Q8WCo+KCZfeCkpLT5+WCgpOwp9CgoKLy8gZmlsZSBtYWluLmNwcAovLyNpbmNsdWRlICJ5LmgiCgppbnQgbWFpbigpCnsKICBZIHk7CiAgcmV0dXJuIDA7Cn0=