Является ли `reinterpret_cast` безопасным для перехода из производного -> памяти -> базового при наличии правильных статC++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Является ли `reinterpret_cast` безопасным для перехода из производного -> памяти -> базового при наличии правильных стат

Сообщение Anonymous »


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
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»