问题
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