Aligned storage and standard layout

Viewed 882

Consider the following C++11 code:

#include <type_traits>

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

struct foo
{
    std::aligned_storage<sizeof(bar),alignof(bar)>::type m_storage;
};

bar is not standard layout because of the virtual function do_bar(). However, foo is standard layout as the type provided by std::aligned_storage is a POD type and foo satisfies all the other requirements for standard layout types.

What happens then when I use the m_storage storage with placement new to construct an instance of bar? E.g.,

foo f;
::new(static_cast<void *>(&f.m_storage)) bar();

Is this legal? Can I use this to cheat my way around restrictions about standard layout types?

3 Answers
Related