Reputation: 7824
I am having the problem that my class destructor is called when the class is constructed. Consider the following test program:
#include <iostream>
#include <vector>
using namespace std;
class X
{
public:
X() { cout << "X::X()" << endl; };
~X() { cout << "X::~X()" << endl; };
};
class Y : public X
{
public:
Y() : X() { cout << "Y::Y()" << endl; };
~Y() { cout << "Y::~Y()" << endl; };
};
int main() {
vector<Y> a;
a.resize(10);
while(true) ;
return 0;
}
The output (from before the loop) is
X::X()
Y::Y()
Y::~Y()
X::~X()
I don't understand the behaviour of the above snippet:
Upvotes: 8
Views: 257
Reputation: 98526
The prototype of std::vector::resize()
is:
void resize( size_type count, T value = T() );
So it creates a temporary default value to be inserted into the vector (your constructor call), then it is copy-constructed 10 times into the vector (you do not log those), and then the temporary is destroyed (your destructor call).
Note that things have changed for C++11. Now there are two overloads:
void resize( size_type count );
void resize( size_type count, const value_type& value);
So, if you use a proper C++11 compiler you will call the first overload and your values will be value-initialized, that is it will use the default constructor.
Upvotes: 10