【发布时间】:2017-01-12 23:08:12
【问题描述】:
由于 C++ 别名规则,您不能随意将 (一个 int*) 指向 char 数组,这似乎达成了一些共识。
从另一个问题——Generic char[] based storage and avoiding strict-aliasing related UB——看来,它似乎可以通过放置 new 来(重新)使用存储。
alignas(int) char buf[sizeof(int)];
void f() {
// turn the memory into an int: (??) from the POV of the abstract machine!
::new (buf) int; // is this strictly required? (aside: it's obviously a no-op)
// access storage:
*((int*)buf) = 42; // for this discussion, just assume the cast itself yields the correct pointer value
}
那么,上面的 C++ 是否合法并且是真正需要的放置 new 以使其合法吗?
【问题讨论】:
-
高度相关的潜在骗子:stackoverflow.com/questions/40873520/…
-
建议更改标题的措辞,以明确您的意思是通过
int左值访问 char 数组。您可以通过其他方式将 int 放入 char 数组中,例如memcpy进进出出。 -
在 C 中(在 C++ 中不确定)指向 char 的指针被排除在别名规则之外(即允许别名)。要反过来工作,您通常使用带有 int 和 char 成员的类型双关联。当然,剩下的问题是对齐,但我假设底层架构允许非对齐访问和/或指针正确对齐。
标签: c++ language-lawyer primitive-types strict-aliasing placement-new