How to initialize a vector of pointers

A zero-size vector of pointers:

std::vector<int*> empty;

A vector of NULL pointers:

std::vector<int*> nulled(10);

A vector of pointers to newly allocated objects (not really initialization though):

std::vector<int*> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
    stuff.push_back(new int(i));

Initializing a vector of pointers to newly allocated objects (needs C++11):

std::vector<int*> widgets{ new int(0), new int(1), new int(17) };

A smarter version of #3:

std::vector<std::unique_ptr<int>> stuff;
stuff.reserve(10);
for( int i = 0; i < 10; ++i )
    stuff.emplace_back(new int(i));

Leave a Comment