Is it undefined behavior to reinterpret_cast an object of an unrelated type to an empty class

对着背影说爱祢 提交于 2019-12-13 01:07:35

问题


It it undefined behavior to cast an unrelated type to an empty base class? And then use that address to construct a derived type that inherits from that empty base? For example

class Derived : public EmptyBase {
public:
    template <typename T>
    Derived(T&& t) : EmptyBase{std::forward<T>(t)} {}
    using EmptyBase::print;
};

and then is it undefined to do something like this

static auto shim = 1;
auto derived = Derived{*reinterpret_cast<EmptyBase*>(&shim)};
derived.print();

The standard guarantees that empty bases must be optimized away in a standard layout struct, but not sure about whether something like this is allowed to construct a derived class


回答1:


Derived{*reinterpret_cast<EmptyBase*>(&shim)}

Derived's constructor accesses the value representation of its parameter to initialize its base class. The parameter has the type EmptyBase&&. But there is no EmptyBase object at that address; there is an int at that address.

Therefore, you are accessing the value representation of an int through a glvalue (EmptyBase&&) of a type unrelated to int. That violates strict aliasing.

So no, you can't just do that.

And no, it doesn't matter that EmptyBase has no subobjects. Copying an object accesses its value representation. Even if the derived class will overwrite anything it does (since the empty base class has no storage of its own).



来源:https://stackoverflow.com/questions/48273253/is-it-undefined-behavior-to-reinterpret-cast-an-object-of-an-unrelated-type-to-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!