[英]Aliasing accesses through a std::bit_cast()ed pointer
Violating strict-aliasing rules yields undefined behavior, eg when sending a struct over the network into a char buffer, and then that char pointer is C-style/ std::reinterpret_cast()
casted to a struct pointer.违反严格别名规则会产生未定义的行为,例如,当通过网络将结构发送到 char 缓冲区时,然后该 char 指针被 C 风格/
std::reinterpret_cast()
强制转换为 struct 指针。
The C++ std::bit_cast()
function looks like it could be used to cast such pointers in an (implementation?) defined way, ie without violating strict-aliasing rules. C++
std::bit_cast()
function看起来可以用于以(实现?)定义的方式转换此类指针,即不违反严格混叠规则。
Example:例子:
#include <sys/types.h>
#include <netinet/in.h>
#include <bit>
int get_sock_addr(const struct sockaddr *a)
{
struct sockaddr_in *x = std::bit_cast<struct sockaddr_in*>(a);
return x->sin_addr.s_addr;
}
So the caller of get_sock_addr()
somehow obtained a sockaddr
pointer and has determined that it actually points to a sockaddr_in
struct.所以
get_sock_addr()
的调用者以某种方式获得了一个sockaddr
指针,并确定它实际上指向一个sockaddr_in
结构。
So, is such pointer casting via std::bit_cast()
a valid use-case?那么,这种通过
std::bit_cast()
进行的指针转换是一个有效的用例吗?
Or does it somehow yield undefined behavior, as well?或者它是否也会以某种方式产生未定义的行为?
If it's defined behavior, does the standard classify such pointer-casting as implementation-defined behavior?如果它是定义的行为,标准是否将这种指针转换归类为实现定义的行为?
The std::bit_cast()
proposal mentions: std::bit_cast()
提案提到:
If no value representation corresponds to To's object representation then the returned value is unspecified.
如果没有值表示对应于 To 的 object 表示,则返回值未指定。
So is a standard-conforming compiler possible where different pointer representations are incompatible such that they can't correspond to each other?那么在不同的指针表示不兼容以至于它们不能相互对应的情况下,是否可以使用符合标准的编译器?
Converting the pointer value is irrelevant.转换指针值是无关紧要的。 What matters is the object.
重要的是 object。 You have a pointer to an object of type X, but the pointer's type is Y. Trying to access the object of type X through a pointer/reference to unrelated type Y is where the UB comes from.
您有一个指向 X 类型的 object 的指针,但指针的类型是 Y。尝试通过指向无关类型 Y 的指针/引用访问 X 类型的 object 是 UB 的来源。
How you obtained those pointers is mostly irrelevant.您如何获得这些指针大多无关紧要。 So
bit_cast
is no better than reinterpret_cast
in this regard.所以
bit_cast
在这方面并不比reinterpret_cast
好。
If there is no sockaddr_in
there, then you can't pretend that there is one.如果那里没有
sockaddr_in
,那么你就不能假装有一个。 However, it's possible that implicit object creation in C++20 already solves this matter, depending on your code.但是,根据您的代码,在 C++20 中创建隐式 object可能已经解决了这个问题。 If it does, then it still doesn't matter how you get the pointer.
如果是这样,那么如何获得指针仍然无关紧要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.