Topic: destructor called by vector::resize()
Author: hinnant@_anti-spam_metrowerks.com (Howard Hinnant)
Date: 1999/04/21 Raw View
In article <0r6xZcFz00019AS0ge@andrew.cmu.edu>, Hwee Kuan Lee
<hwee+@andrew.cmu.edu> wrote:
> i found that when the resize function of a vector class is called, the
> destructor of the vector's element type is also called. example:
>
> class X {
> public:
> X() {
> cout<<"construct"<<endl;
> }
> ~X() {
> cout<<"destruct"<<endl;
> }
> };
>
> main () {
>
> vector<X> vx;
>
> vx.resize(2);
>
> cout<<"----- end program "<<endl;
>
> }
>
> this program when compiled with egcs-g++ on linux red hat will yield,
>
> construct
> destruct
> ----- end program
> destruct
> destruct
>
> i have a few questions regarding this output,
>
> first, why is the destructor called when resize function is called?
> next is that why is the constructor called once, while destructor
> is called three times? construct once, but destroy three times?
I have modified your program just a bit to aid explanation:
#include <iostream>
#include <vector>
using namespace std;
class X {
public:
X() {
cout<<"construct"<<endl;
}
X(const X&)
{
cout << "copy construct\n";
}
~X() {
cout<<"destruct"<<endl;
}
};
int
main () {
cout<<"----- begin program "<<endl;
vector<X> vx;
cout<<"----- begin resize "<<endl;
vx.resize(2);
cout<<"----- end program "<<endl;
}
Using Metrowerks CodeWarrior this outputs:
----- begin program
----- begin resize
construct
copy construct
copy construct
destruct
----- end program
destruct
destruct
(The original test gave the same output as egcs-g++)
Now we have the same number of constructions as destructions. A look at
the vector::resize signiture will help explain things further:
void resize(size_type sz, T c = T());
So X() is constructed to complete the default argument to resize(). Then,
that default constructed argument is copied (via the copy constructor) for
each new element in the vector (twice). After the resize call, the
temporary default argument is destructed. Then at the main closing brace
(after the "end program"), the vector is destructed, resulting in two X's
being destructed.
-Howard
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]