Sha Moomoo
Sha Moomoo

Reputation: 21

Initializing Template Array

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;
        }

Upvotes: 2

Views: 166

Answers (1)

Pubby
Pubby

Reputation: 53027

You can use placement new.

new (&storage[i]) T;

Upvotes: 1

Related Questions