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:
Destructors are called when one of the following events occurs: A local (automatic) object with block scope goes out of scope. An object allocated using the new operator is explicitly deallocated using delete . The lifetime of a temporary object ends.
The derived class must be constructed after the base class so that the derived class constructor can refer to base class data. For the same reason, the derived class destructor must run before the base class destructor. It's very logical: we construct from the inside out, and destroy from the outside in.
Constructors are also called when local or temporary class objects are created, and destructors are called when local or temporary objects go out of scope. You can call member functions from constructors or destructors.
Constructor is used to initialize an object of the class and assign values to data members corresponding to the class. While destructor is used to deallocate the memory of an object of a class. There can be multiple constructors for the same class. In a class, there is always a single destructor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With