C++ Too many destructors called so few objects

R

Ravi

Here is the code (also at http://pastebin.com/yw5z2hnG ):

#include <iostream>
#include <vector>
using namespace std;

class X
{
public:
int i;
X();
~X();
};

X::X()
{
i = 1;
cout << "---constructor" << '\n';
}

X::~X()
{
cout << "***desctructor" << '\n';
}

int main()
{
vector<X> *vx = new vector<X>;
cout << "------------------------------------" << endl;
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
cout << "------------------------------------" << endl;
delete vx;
}

I get the output as:

------------------------------------
---constructor
***desctructor
---constructor
***desctructor
***desctructor
---constructor
***desctructor
***desctructor
***desctructor
---constructor
***desctructor
---constructor
***desctructor
***desctructor
***desctructor
***desctructor
***desctructor
------------------------------------
***desctructor
***desctructor
***desctructor
***desctructor
***desctructor

I do not understand why so many destructors are called.
 
K

Kai-Uwe Bux

Ravi said:
Here is the code (also at http://pastebin.com/yw5z2hnG ):

#include <iostream>
#include <vector>
using namespace std;

class X
{
public:
int i;
X();
~X();
};

X::X()
{
i = 1;
cout << "---constructor" << '\n';
}

X::~X()
{
cout << "***desctructor" << '\n';
}

int main()
{
vector<X> *vx = new vector<X>;

Should you have the habit of allocating vectors dynamically, you might want
to reconsider the rationale for that.
cout << "------------------------------------" << endl;
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
vx->push_back(X());
cout << "------------------------------------" << endl;
delete vx;
}

I get the output as:

------------------------------------
---constructor
***desctructor
---constructor
***desctructor
***desctructor
---constructor
***desctructor
***desctructor
***desctructor
---constructor
***desctructor
---constructor
***desctructor
***desctructor
***desctructor
***desctructor
***desctructor
------------------------------------
***desctructor
***desctructor
***desctructor
***desctructor
***desctructor

I do not understand why so many destructors are called.

Because so many constructors are called: define the copy constructor and
make it also print messages.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top