【发布时间】:2011-10-11 12:16:28
【问题描述】:
我正在尝试模仿矢量 STL 类。我的构造函数调用以下函数,它将在堆上为其分配一些内存。我想初始化每个对象,无论它们是基元还是对象。我不确定实现这一点的语法。我只想调用默认构造函数。带有T(storage[i]); 的行表示该点。
void init_vector(uint reserve)
{
if (reserve == 0) reserve=1;
_size = 0;
storage = (T*)malloc(sizeof(T)*reserve);
if (storage == NULL)
{
assert(false);
}
for (uint i=0; i<reserve; i++)
{
T(storage[i]); ???
}
_reserved = reserve;
}
【问题讨论】:
-
您想要的几乎就是
std::vector的实现方式;构造由分配器的construct()函数执行(该函数又使用全局placement-new)。
标签: c++ stl vector constructor initialization