初始化模板数组
我正在尝试模仿向量 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;
}
I'm trying to mimic the vector STL class. My constructor calls the following function which will allocate some memory for it on the heap. I want to initialize each of the objects, whether they be primitives or objects. I'm not sure of the syntax to achieve this. I just want the default constructor to be called. The line with T(storage[i]);
shows the spot.
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用新展示位置。
You can use placement new.