#include <vector>
#include <iostream>
using namespace std;
class Test
{
		public:
		Test()
		{
				cout<<"In TEST constructor"<<endl;
		}
		~Test()
		{
				cout<<"In TEST destructor"<<endl;
		}
 
};
int main()
{
		Test t1;
		vector<Test> vec;
		vec.push_back( t1 );
		cout<<"About to clear vector"<<endl;
		vec.clear();
 
 
}

I suspect I'm missing something fundamental. When I run this, I get the cout for the destructor twice. (Why would clearing the vector cause the destructor of Test to be called?)

./Temp
In TEST constructor
About to clear vector
In TEST destructor
In TEST destructor

A guess:

#include <vector>
#include <iostream>
using namespace std;
class Test
{
		public:
		Test()
		{
				cout<<"In TEST constructor"<<endl;
		}
		~Test()
		{
				cout<<"In TEST destructor"<<endl;
		}

};
int main()
{
		Test t1;
		vector<Test> vec;
		vec.push_back( t1 );
		cout<<"About to clear vector"<<endl;
		vec.clear();
      cout << "done\n";
}

/* my output
In TEST constructor
About to clear vector
In TEST destructor
done
In TEST destructor
*/

The constructor code is the construction of t1. Then a copy constructor is used when it is pushed back on the vector. When the clear() is called, it calls the destructor for the object in the vector. Then t1's destructor is called when it goes out of scope.

Makes sense. To test, I made it a vector of Test * and only got one destruction call:

#include <vector>
#include <iostream>
using namespace std;
class Test
{
		public:
		Test()
		{
				cout<<"In TEST constructor"<<endl;
		}
		~Test()
		{
				cout<<"In TEST destructor"<<endl;
		}
};
int main()
{
		Test t1;
		vector<Test *> vec;
		vec.push_back( &t1 );
		cout<<"About to clear vector"<<endl;
		vec.clear();
		cout<<"done"<<endl;
 
}

./Temp
In TEST constructor
About to clear vector
done
In TEST destructor

----------------
I would imagine then that if my classes are large that I would be much better served (performance wise) to be holding pointers to my objects than copies of my objects....

[edit](Never mind)

I can't help but wonder about your intent with pushing an address. Let's say you were reading records from a file into a temporary line of text. You could avoid the constructor and pass only a pointer to the temporary text, but you wouldn't be keeping unique copies of the data that you'd read. In the end you'd have a pile of pointers all pointing to something that is no longer there.

Be careful with what you are doing, and try to avoid premature optimization. Perhaps you could provide a little more of the 'big picture'; but in the end be careful.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.