Can Aliasing Problems be Avoided with const Variables

后端 未结 5 1387
梦谈多话
梦谈多话 2020-12-31 22:42

My company uses a messaging server which gets a message into a const char* and then casts it to the message type.

I\'ve become concerned about this afte

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 23:02

    The other answer answered the question well enough (it's a direct quotation from the C++ standard in https://isocpp.org/files/papers/N3690.pdf page 75), so I'll just point out other problems in what you're doing.

    Note that your code may run into alignment problems. For example, if the alignment of MessageJ is 4 or 8 bytes (typical on 32-bit and 64-bit machines), strictly speaking, it is undefined behaviour to access an arbitrary character array pointer as a MessageJ pointer.

    You won't run into any problems on x86/AMD64 architectures as they allow unaligned access. However, someday you may find that the code you're developing is ported to a mobile ARM architecture and the unaligned access would be a problem then.

    It therefore seems you're doing something you shouldn't be doing. I would consider using serialization instead of accessing a character array as a MessageJ type. The only problem isn't potential alignment problems, an additional problem is that the data may have a different representation on 32-bit and 64-bit architectures.

提交回复
热议问题