Hi,
I've got a problem with a program that boils down to strange behavior by the vector container class. It seems to not want to call constructors enough but calls destructors too many times:
#include <vector>
#include <iostream>
using std::cout;
int constructor_count=1,destructor_count=1;
class obj{public:
obj(){
cout<<"C: "<<constructor_count++<<'\n';
}
~obj(){
cout<<"D: "<<destructor_count++<<'\n';
}
};
int main(){
cout<<"Declare v1:\n";
std::vector<obj> v1(3);
cout<<"\nResize v1:\n";
v1.resize(4);
cout<<"\n\nDeclare v2:\n";
std::vector<obj> v2(3,obj());
cout<<"\nResize v2:\n";
v2.resize(4);
std::cin.get();
}
/*Output: - - -
Declare v1:
C: 1
D: 1
Resize v1:
C: 2
D: 2
D: 3
D: 4
D: 5
D: 6
Declare v2:
C: 3
D: 7
Resize v2:
C: 4
D: 8
D: 9
D: 10
D: 11
D: 12
*/
I was storing handles to window objects in a "wrapper class", and I got an error every time I resized the vector so that it needed to allocate more memory (ie it was fine if I called reserve(1000); at the start), and I've traced it down to this.
Is there any way to make the vector call the constructors properly?
Thanks for your help.