2
votes

I wanted to see if I could initialize a vector of objects in a single line, so I wrote the following example:

vector<Bar*> bar(5, new Bar());

bar[3]->hit++;
for (int i = 0; i < 5; i++)
    cout << bar[i]->hit << endl;

But when I run it, I get:

1
1
1
1
1

It seems to use the same new Bar() for all the pointers. Is it possible to initialize vectors of object pointers to point to different objects?

3
You can, using some std::generate magic, but the question is, why would you want to? - avakar

3 Answers

3
votes

All your pointers point to the same location, so the result is expected.

vector<Bar*> bar(5, new Bar());

doesn't create a new Bar for all 5 objects, but uses the value returned by new Bar(), which is a pointer to a memory location, to generate the vector.

To get the result you expect, you can use std::generate:

Bar* newBar() { return new Bar(); }

//...

vector<Bar*> bar(5);
std::generate(bar.begin(),bar.end(),newBar);

or simply

std::generate(bar.begin(),bar.end(), []{return new Bar();});

if C++11 is an option.

The output for this would be

0
0
0
1
0
1
votes

Initializing a vector with several different values requires C++11 and the support for initializer lists:

std::vector<Bar*> v { new Bar, new Bar, new Bar, new Bar };

You can probably use a library like Boost.Assign in versions before C++11.

0
votes

From the spec:

Effects: Constructs a vector with n copies of value [...]

where n is the first and value the second argument.