Why is a C ++ class destructor called a construct?

I had a problem calling my destructor class when building the class. 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; } 

Conclusion (from cycle to end)

 X::X() Y::Y() Y::~Y() X::~X() 

I do not understand the behavior of the above snippet:

  • Why is only one item created?
  • Why are destructors called?
+8
c ++ inheritance constructor destructor
source share
1 answer

The prototype of std::vector::resize() is:

 void resize( size_type count, T value = T() ); 

Thus, it creates a temporary default value that needs to be inserted into the vector (your constructor call), then it is copied 10 times into the vector (you do not register them), and then the temporary one is destroyed (your destructor is called).

Note that for C ++ 11, everything has changed. Now there are two overloads:

 void resize( size_type count ); void resize( size_type count, const value_type& value); 

So, if you use the correct C ++ 11 compiler, you will call the first overload, and your values ​​will be initialized with a value, that is, it will use the default constructor.

+10
source share

All Articles