c++ - 为什么这里会出现字节顺序问题?

标签 c++ endianness

我正在阅读 this thread关于指针别名规则,一个答案给出了以下示例,其中提到了字节顺序的潜在问题,我想知道是否有人可以告诉我以下代码中的字节顺序问题什么

struct Msg
{
   unsigned int a;
   unsigned int b;
};

int main()
{
   // Pass data to something; if the implementer of this API were
   // strict-aliasing-aware, he would have taken a char*, not a unsigned int*
   Msg* msg = new Msg();
   msg->a = 1;
   msg->b = 2;

   // stupidBuffer is an alias for msg.
   // yes I know there are endianess problems here (WHY??), but my API is stupid and 
   // only works for one platform
   unsigned int* stupidBuffer = reinterpret_cast<unsigned int*>(msg);

   SendToStupidApi( stupidBuffer );   
}

最佳答案

没有任何字节序问题。只要 StupidApi 不涉及通过网络发送它或在平台之间进行序列化,那么就根本没有字节顺序问题。

关于c++ - 为什么这里会出现字节顺序问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7293291/

相关文章:

c++ - 我可以将VB代码转换为C++代码吗

c++ - 在 MSVC ABI 中,如何可靠地找到仅给出 (void*) 的 vtable?

c++ - Qt:在QNetworkAccessManager中发送请求后连接信号

c++ - 将字节数组转换为结构指针取决于字节序或内存对齐方式?

c - 如何为可移植程序正确使用 gcc -fsso-struct?

c++ - 是否有 HTML Tidy 的替代品?

c++ - MPI_Comm_Rank的段错误

c++ - Golang 中 binary.write 的 C++ 等价物是什么?

c++ - 测试 C++ 代码的字节序无关性

c++ - 访问 float 的 4 个字节是否会破坏 C++ 别名规则