KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
When I create a std::vector of objects, the constructor of these objects is not always called. #include <iostream> #include <vector> using namespace std; struct C { int id; static int n; C() { id = n++; } // not called // C() { id = 3; } // ok, called }; int C::n = 0; int main() { vector<C> vc; vc.resize(10); cout << "C::n = " << C::n << endl; for(int i = 0; i < vc.size(); ++i) cout << i << ": " << vc[i].id << endl; } This is the output I get: C::n = 1 0: 0 1: 0 2: 0 ... This is what I would like: C::n = 10 0: 0 1: 1 2: 2 ... In this example, am I forced to resize the vector and then initialise its elements "manually"? Could the reason be that the elements of a vector are not initialised in an ordered way, from the first to the last, and so I cannot obtain a deterministic behaviour? What I would like to do, is to easily count the number of objects created in a program, in different containers, in different points of the code, and to give a single id to each of them. Thank's!
Tags (comma-separated)
Save Edits
Cancel