gpt4 book ai didi

c++ - 如何在不违反类型别名规则的情况下解释消息负载?

转载 作者:IT老高 更新时间:2023-10-28 12:41:52 25 4
gpt4 key购买 nike

我的程序通过网络接收消息。这些消息被一些中间件反序列化(即我无​​法更改的其他人的代码)。我的程序接收到如下所示的对象:

struct Message {
int msg_type;
std::vector<uint8_t> payload;
};

通过检查 msg_type,我可以确定消息负载实际上是一个 uint16_t 值数组。我想在没有不必要的拷贝的情况下读取该数组。

我的第一个想法是这样做:

const uint16_t* a = reinterpret_cast<uint16_t*>(msg.payload.data());

但是从 a 读取似乎违反了标准。这是第 3.10.10 条:

If a program attempts to access the stored value of an object through a glvalue of other than one of the following types the behavior is undefined:

  • the dynamic type of the object,
  • a cv-qualified version of the dynamic type of the object,
  • a type similar (as defined in 4.4) to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to the dynamic type of the object,
  • a type that is the signed or unsigned type corresponding to a cv-qualified version of the dynamic type of the object,
  • an aggregate or union type that includes one of the aforementioned types among its elements or nonstatic data members (including, recursively, an element or non-static data member of a subaggregate or contained union),
  • a type that is a (possibly cv-qualified) base class type of the dynamic type of the object,
  • a char or unsigned char type.

在这种情况下,a 将是泛左值,而 uint16_t* 似乎不符合任何列出的条件。

那么如何将有效负载视为 uint16_t 值的数组而不调用未定义的行为或执行不必要的复制?

最佳答案

如果您要一个一个地使用这些值,那么您可以将 memcpy 写入 uint16_t,或者写入 payload[0] + 0x100 * payload[ 1] 等,关于你想要的行为。这不会是“低效的”。

如果你必须调用一个只接受 uint16_t 数组的函数,而你又不能改变传递 Message 的结构体,那么你就不走运了。在标准 C++ 中,您必须制作拷贝。

如果您使用 gcc 或 clang,另一种选择是在编译相关代码时设置 -fno-strict-aliasing

关于c++ - 如何在不违反类型别名规则的情况下解释消息负载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com