4

请教大家一个 C++内存分配后对象初始化的问题

 2 years ago
source link: https://www.v2ex.com/t/795873
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  C++

请教大家一个 C++内存分配后对象初始化的问题

  GKCY · 6 小时 16 分钟前 · 407 次点击

一直写 Java,最近用到 C++,有个问题不是很明白。 现在有个 allocator 用来分配内存,Key 是个类。 Key* keys = allocator.alloc(sizeof(key) * 10); 我的理解这样 keys 数组是不能直接用的,因为只分配了内存,类没有初始化。 但是这该怎么初始化呢?我能想到的笨方法是,先分配一个 buf 内存,然后循环里通过 new (buf)一个个初始化,但是这样感觉代码很丑陋,之前没接触过 C++,问题可能很蠢,请大佬不要介意。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK