Re: Problems storing objects in a vector and incrementing a static counter in C++
Hello Bruno,
std::vector<MyClass> m;
m.resize(5);
for(i=0; i<5;i++)
{
m.at(i);
cout << endl << "LOOP"<<'\t';
m[i].DisplayMyClassObject();
}
cout << endl << endl;
return (0); // this should not be always 0
}
A problem with what your doung is that the resize creates a temporary
"MyClass" copies it & destroys the temp.
From the VC6 (which is what you say you use) help on vector::resize...
void resize(size_type n, T x = T());
The second param defaults to make a temporary which is then copied to all
entries including your ID (as you have not specified a copy constructor the
compiler makes one for you which just clones the contents). resize() doesn't
as you found call the constructor for each entry. The vector destructor does
call the destructor on each of the copies though causing your counter to get
out of synch.
You can construct the elements manually using placement new (but you still
waste the time copying with the resize).
------------------------------------------------------------------------
std::vector< MyClass > m;
m.resize(5);
for(i=0; i<5;i++)
{
::new( &m[i] ) MyClass;
cout << endl << "LOOP"<<'\t';
m[i].DisplayMyClassObject();
}
// OUTPUTS...
CONSTRUCTOR ID 1 Cn 1
CONSTRUCTOR ID 2 Cn 2
CONSTRUCTOR ID 3 Cn 3
CONSTRUCTOR ID 4 Cn 4
DESTRUCTOR ID 4 Cn 3
CONSTRUCTOR ID 4 Cn 4
LOOP ID 4 Cn 4
CONSTRUCTOR ID 5 Cn 5
LOOP ID 5 Cn 5
CONSTRUCTOR ID 6 Cn 6
LOOP ID 6 Cn 6
CONSTRUCTOR ID 7 Cn 7
LOOP ID 7 Cn 7
CONSTRUCTOR ID 8 Cn 8
LOOP ID 8 Cn 8
DESTRUCTOR ID 4 Cn 7
DESTRUCTOR ID 5 Cn 6
DESTRUCTOR ID 6 Cn 5
DESTRUCTOR ID 7 Cn 4
DESTRUCTOR ID 8 Cn 3
DESTRUCTOR ID 3 Cn 2
DESTRUCTOR ID 2 Cn 1
DESTRUCTOR ID 1 Cn 0
------------------------------------------------------------------------
Or... you could rewite the copy constructor... This would do what I think
you expected your code to do originally.
class MyClass
{
public:
void DisplayMyClassObject(void);
MyClass();
MyClass(const MyClass& src) { ::new(this) MyClass; } // don't copy actually
make fresh one
....
};
std::vector< MyClass > m;
m.resize(5);
for(i=0; i<5;i++)
{
cout << endl << "LOOP"<<'\t';
m[i].DisplayMyClassObject();
}
// OUTPUTS
CONSTRUCTOR ID 1 Cn 1
CONSTRUCTOR ID 2 Cn 2
CONSTRUCTOR ID 3 Cn 3
CONSTRUCTOR ID 4 Cn 4
CONSTRUCTOR ID 5 Cn 5
CONSTRUCTOR ID 6 Cn 6
CONSTRUCTOR ID 7 Cn 7
CONSTRUCTOR ID 8 Cn 8
CONSTRUCTOR ID 9 Cn 9
DESTRUCTOR ID 4 Cn 8
LOOP ID 5 Cn 8
LOOP ID 6 Cn 8
LOOP ID 7 Cn 8
LOOP ID 8 Cn 8
LOOP ID 9 Cn 8
DESTRUCTOR ID 5 Cn 7
DESTRUCTOR ID 6 Cn 6
DESTRUCTOR ID 7 Cn 5
DESTRUCTOR ID 8 Cn 4
DESTRUCTOR ID 9 Cn 3
DESTRUCTOR ID 3 Cn 2
DESTRUCTOR ID 2 Cn 1
DESTRUCTOR ID 1 Cn 0
------------------------------------------------------------------------
Hope this helps,
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]