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?
All your pointers point to the same location, so the result is expected.
doesn’t create a new
Barfor all 5 objects, but uses the value returned bynew Bar(), which is a pointer to a memory location, to generate the vector.To get the result you expect, you can use
std::generate:or simply
if C++11 is an option.
The output for this would be