小编Mik*_*ike的帖子

来自void指针缓冲区的struct实例化

这里有一些看起来很有趣的C++代码,但我知道它有效.

有一个结构定义,在程序中我们使用void指针分配内存.然后使用分配的缓冲区创建结构.

这是一些代码

typedef struct{
 char buffer[1024];
} MyStruct

int main()
{
   MyStruct* mystruct_ptr = 0;

   void* ptr = malloc(sizeof(MyStruct));

   // This is the line that I don't understand
   mystruct_ptr = new (ptr) MyStruct();

   free(ptr);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

代码有更多的东西,但这是它的要点.

我没有测试过这段代码,但我正在查看的代码经过了很好的测试,并且可以运行.但是怎么样?

谢谢.

编辑:修复了内存泄漏.

c++ struct allocation void-pointers placement-new

4
推荐指数
2
解决办法
1278
查看次数

标签 统计

allocation ×1

c++ ×1

placement-new ×1

struct ×1

void-pointers ×1