相关疑难解决方法(0)

不使用placement new返回的指针时C++严格别名

这可能会导致未定义的行为吗?

uint8_t storage[4];

// We assume storage is properly aligned here.
int32_t* intPtr = new((void*)storage) int32_t(4);

// I know this is ok:
int32_t value1 = *intPtr;
*intPtr = 5;

// But can one of the following cause UB?
int32_t value2 = reinterpret_cast<int32_t*>(storage)[0];
reinterpret_cast<int32_t*>(storage)[0] = 5;
Run Code Online (Sandbox Code Playgroud)

char有严格别名的特殊规则.如果我使用char而不是 uint8_t它仍然是未定义的行为?还有什么变化?

正如成员DeadMG指出的那样,reinterpret_cast依赖于实现.如果我改用C风格的演员(int32_t*)storage,会有什么变化?

c++ strict-aliasing placement-new language-lawyer type-punning

8
推荐指数
2
解决办法
735
查看次数