Quote Originally Posted by Micko
How to explain this:
Code:
#include <iostream>
#include <vector>

using namespace std;

class Test
{
    int x;
    public:
        Test()
        {
            cout << "Constructor!" << endl;
        }
        ~Test()
        {
            cout << "Destructor!" << endl;
        }
};
 
int main()
{
    vector <Test> v;
    Test t1, t2, t3;
    v.push_back(t1);
    v.push_back(t2);
    v.push_back(t3);
    
    v.clear();
}
My output is:
Constructor!
Constructor!
Constructor!
Destructor!
Destructor!
Destructor!
Destructor!
Destructor!
Destructor!
You're pointing out the discrepancy between the number of times the constructor and destructor have been called? You need to add a copy constructor to your code and then see what happens. Each push_back call is calling the copy constructor to create a copy of the objects you push onto the vector. This is where the 3 missing constructor calls are hiding.

Code:
#include <iostream>
#include <vector>

using namespace std;

class Test
{
    int x;
    public:
        Test()
        {
            cout << "Constructor!" << endl;
        }
        Test(const Test& test)
        {
            x = test.x;
            cout << "Copy constructor!" << endl;
        }
        ~Test()
        {
            cout << "Destructor!" << endl;
        }
};

int main()
{
    vector <Test> v;
    Test t1, t2, t3;
    v.push_back(t1);
    v.push_back(t2);
    v.push_back(t3);
    
    v.clear();
}
Should generate output similar to:
Constructor!
Constructor!
Constructor!
Copy constructor!
Copy constructor!
Copy constructor!
Destructor!
Destructor!
Destructor!
Destructor!
Destructor!
Destructor!