I notice <vector> uses the constructor once and then uses the copy constructor for a class when creating all the other elements of a vector chain.
So, if I have:
class MyClass {
MyClass() {
cout << "Constructor" << endl;
}
~MyClass() {
cout << "Deconstructor" << endl;
}
MyClass(const MyClass& mc) {
cout << "Copy Constructor" << endl;
}
}
calling as a vector array (sorry, don't know of a better term!)
// in main...
vector<MyClass> mc(2);
Instead of:-
"Constructor"
"Constructor"
"Destructor"
"Destructor"
I get:
"Constructor"
"Copy Constructor"
"Copy Constructor"
"Destructor"
"Destructor"
"Destructor"
Which is fine... but I'm developing classes where each class gets a unique ID (incremented from a static int in the class) in the Constructor and it would be preferable to have the constructors called independantly. Otherwise, I end up with 'missing' IDs from the 'temporary' classes called via the vector.
The only way I can think of is to
1. Create a regular array dynamically.
2. vector<MyClass> mc(array, array+size)
3. Delete the previous array.
Is there a better way to ensure the constructor is called every time (for each allocated instance in the vector array) and not when a temporary one is being used via a copy constructor? I wish I could phrase this better, but I'm struggling to describe it and apologise for the confusion.
[edit - simpler - can I get the constructor called for each element in the vector<class> var(num_elements) when the vector array is declared? (like you would in a regular array) ]