Является ли `reinterpret_cast` безопасным для перехода из производного -> памяти -> базового при наличии правильных стат ⇐ C++
-
Anonymous
Является ли `reinterpret_cast` безопасным для перехода из производного -> памяти -> базового при наличии правильных стат
I'm writing C++14 code which needs to deserialize objects as fast as possible.
The serialization is in memory and occurs in the same process as the deserialization.
Consider this:
struct Base { Base(const int a) : a {a} { } int a; }; struct Derived : public Base { Derived(const int a, const int b, const int c) : Base {a}, b {b}, c {c} { } int b; int c; }; Assume all those objects will only contain int members.
What I'd like is for some memory region to contain contiguous memory representations of those objects, for example:
[Base] [Base] [Derived] [Base] [Derived] [Derived] Let's just pretend you may know if it's Derived or not from the Base::a member.
Is the following code safe given the two static assertions?
#include struct Base { Base(const int a) : a {a} { } int a; }; struct Derived : public Base { Derived(const int a, const int b, const int c) : Base {a}, b {b}, c {c} { } int b; int c; }; static_assert(alignof(Derived) == alignof(Base), "`Base` and `Derived` share the same alignment"); static_assert(sizeof(Derived) == sizeof(Base) + 2 * sizeof(int), "Size of `Derived` is expected"); int main() { const Derived d {1, 2, 3}; const auto dP = reinterpret_cast(&d); auto& base = reinterpret_cast(*dP); std::cout
Источник: https://stackoverflow.com/questions/780 ... the-proper
I'm writing C++14 code which needs to deserialize objects as fast as possible.
The serialization is in memory and occurs in the same process as the deserialization.
Consider this:
struct Base { Base(const int a) : a {a} { } int a; }; struct Derived : public Base { Derived(const int a, const int b, const int c) : Base {a}, b {b}, c {c} { } int b; int c; }; Assume all those objects will only contain int members.
What I'd like is for some memory region to contain contiguous memory representations of those objects, for example:
[Base] [Base] [Derived] [Base] [Derived] [Derived] Let's just pretend you may know if it's Derived or not from the Base::a member.
Is the following code safe given the two static assertions?
#include struct Base { Base(const int a) : a {a} { } int a; }; struct Derived : public Base { Derived(const int a, const int b, const int c) : Base {a}, b {b}, c {c} { } int b; int c; }; static_assert(alignof(Derived) == alignof(Base), "`Base` and `Derived` share the same alignment"); static_assert(sizeof(Derived) == sizeof(Base) + 2 * sizeof(int), "Size of `Derived` is expected"); int main() { const Derived d {1, 2, 3}; const auto dP = reinterpret_cast(&d); auto& base = reinterpret_cast(*dP); std::cout
Источник: https://stackoverflow.com/questions/780 ... the-proper
Мобильная версия