Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the destructor of a C++ class called upon construction?

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:

  1. Why is only a single element constructed?
  2. Why are the destructors called?
like image 869
janoliver Avatar asked Mar 17 '14 11:03

janoliver


People also ask

Why is my destructor being called?

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.

Why is destructor of derived class called first?

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.

How constructors and destructors are called?

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.

What is the purpose of a constructor destructor?

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.


1 Answers

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.

like image 54
rodrigo Avatar answered Sep 28 '22 00:09

rodrigo