[英]Is it safe to reinterpret_cast<bool*> zeroed out memory?
Context: 语境:
I have a chunk of memory that's shared between two processes via shm_open
. 我有一块内存,通过
shm_open
在两个进程之间共享。 I am guaranteed that after ftruncate
ing and mmap
ing it, the whole chunk has the bit pattern 00000...
. 我保证在
ftruncate
和mmap
之后,整个块的位模式为00000...
I need to share a boolean value across the two processes. 我需要在两个进程之间共享一个布尔值。
A more concrete question: 一个更具体的问题:
Is the following guaranteed to be okay (the assertion doesn't fail and UB does not occur) on reasonable POSIX systems? 在合理的POSIX系统上,以下保证是否正常(断言不会失败并且UB不会发生)?
void *my_shared_memory_region = calloc(1024, 1);
bool *my_bool = reinterpret_cast<bool*>(my_shared_memory_region);
assert(*my_bool == false);
I believe that there are some restrictions on the actual values that can live inside of a bool
, so I'm not sure. 我相信对于一个可以存在于
bool
的实际值有一些限制,所以我不确定。 I think this question is distinct from this one because reinterpret_cast
doesn't do the same kind of conversions that C-style casts do. 我觉得这个问题是来自不同的这一个 ,因为
reinterpret_cast
并不尽同一种转换的是C-风格的转换做。
The core issue - even if the memory's all zeros, is it valid to read from it as if from a properly initialised bool
- is the same as for this question . 核心问题 - 即使内存全为零,从正确初始化的
bool
读取它是有效的 - 与此问题相同。
Long story short: it's undefined behaviour that works on common systems but isn't guaranteed portable. 长话短说:它是未定义的行为 ,适用于常见系统但不保证可移植。 Specific implementations are allowed to document behaviour for cases the Standard leaves undefined, so it's worth doing some research for the specific platforms/compilers you care about.
允许特定实现来记录标准版未定义的情况下的行为,因此值得对您关心的特定平台/编译器进行一些研究。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.