在C++中将char-array转换为POD数组

Rom*_*man 3 c++ pointers dynamic-memory-allocation reinterpret-cast c++11

编写下面代码的正确方法是什么?

我有一个内存管理器,它提供了我char *的,但我需要使用数组uint32_t.我如何解决严格的别名规则?我理解,对于单个对象,建议只复制内容,memcpy()但对于一组对象,该解决方案是不可接受的.

char* ptr = manager()->Allocate(1000 * sizeof(uint32_));
uint32_t* u32ptr = reinterpret_cast<uint32_t*>(ptr);
....
u32ptr[x] = y;
Run Code Online (Sandbox Code Playgroud)

ala*_*ain 6

您可以使用placement-new:

uint32_t* u32ptr = new(ptr) uint32_t[1000];
Run Code Online (Sandbox Code Playgroud)

请注意,在此之后,存储的有效类型是int32_t,您可能不再使用ptr.您不需要对chars 执行任何特殊操作,因为对于具有普通析构函数的类型,您可以通过重用存储来结束其生命周期.