【问题标题】:Initializing Template Array初始化模板数组
【发布时间】: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


【解决方案1】:

您可以使用placement new

new (&storage[i]) T;

【讨论】:

  • 应该是::new (&amp;storage[i]) T();,我想:我们想要值,而不是默认初始化(想想非类类型);而且我们不希望被重载的placement-new操作符所干扰。
  • 当然,如果只是保留内存,为什么还要在那里构造对象呢?
猜你喜欢
  • 1970-01-01
  • 2012-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多