Anonymous
Неопределенное поведение и переосмысление
Сообщение
Anonymous » 11 апр 2025, 10:02
Я хотел бы понять более подробно, когда Reinterpret_cast безопасен и когда это вызывает неопределенное поведение. Ниже приведена образец программы, которую я собрал для обсуждения. < /P>
Код: Выделить всё
#include
#include
#include
#include
#include
template
void serialize(T const& source, unsigned char* buffer) {
std::memcpy(buffer, &source, sizeof(T));
}
template
T deserialize(unsigned char* buffer) {
T entity;
std::memcpy(&entity, buffer, sizeof(T));
return entity;
}
template
T* view_as(unsigned char* buffer) {
return reinterpret_cast(buffer);
}
struct point {
int x;
int y;
};
bool operator==(point const& lhs, point const& rhs) {
return std::tie(lhs.x, rhs.y) == std::tie(lhs.x, rhs.y);
}
bool operator!=(point const& lhs, point const& rhs) {
return !(lhs == rhs);
}
std::ostream& operator
Подробнее здесь: [url]https://stackoverflow.com/questions/79568146/undefined-behaviour-and-reinterpret-cast[/url]
1744354972
Anonymous
Я хотел бы понять более подробно, когда Reinterpret_cast безопасен и когда это вызывает неопределенное поведение. Ниже приведена образец программы, которую я собрал для обсуждения. < /P> [code]#include #include #include #include #include template void serialize(T const& source, unsigned char* buffer) { std::memcpy(buffer, &source, sizeof(T)); } template T deserialize(unsigned char* buffer) { T entity; std::memcpy(&entity, buffer, sizeof(T)); return entity; } template T* view_as(unsigned char* buffer) { return reinterpret_cast(buffer); } struct point { int x; int y; }; bool operator==(point const& lhs, point const& rhs) { return std::tie(lhs.x, rhs.y) == std::tie(lhs.x, rhs.y); } bool operator!=(point const& lhs, point const& rhs) { return !(lhs == rhs); } std::ostream& operator Подробнее здесь: [url]https://stackoverflow.com/questions/79568146/undefined-behaviour-and-reinterpret-cast[/url]