对齐存储和标准布局

blu*_*rni 9 c++ c++11

考虑以下C++ 11代码:

#include <type_traits>

struct bar
{
    virtual void do_bar() const {}
};

struct foo
{
    std::aligned_storage<sizeof(bar),alignof(bar)>::type m_storage;
};
Run Code Online (Sandbox Code Playgroud)

bar由于虚函数,它不是标准布局do_bar().但是,foo标准布局是提供的类型std::aligned_storage是POD类型并且foo满足标准布局类型的所有其他要求.

当我使用m_storage带有放置的存储new来构造一个实例时会发生bar什么?例如,

foo f;
::new(static_cast<void *>(&f.m_storage)) bar();
Run Code Online (Sandbox Code Playgroud)

这合法吗?我可以用它来欺骗我对标准布局类型的限制吗?

Dav*_*idN 0

在 OSX 的 XCode C++11 编译器选项中尝试过,似乎对我有用。当然,您可能想要执行“::new(static_cast(&f.m_storage)) bar();” 在 foo 的构造函数中,并在 foo 的析构函数中调用其析构函数。