Does anyone know why the STL containers don\'t have virtual destructors?
As far as I can tell, the only benefits are:
If you really need virtual destructor, you can add it in class derived from vector<>, and then use this class as a base class everywhere you need virtual interface. By doing this compilator will call virtual destructor from your base class, which in turn will call non-virtual destructor from vector class.
Example:
#include
#include
using namespace std;
class Test
{
int val;
public:
Test(int val) : val(val)
{
cout << "Creating Test " << val << endl;
}
Test(const Test& other) : val(other.val)
{
cout << "Creating copy of Test " << val << endl;
}
~Test()
{
cout << "Destructing Test " << val << endl;
}
};
class BaseVector : public vector
{
public:
BaseVector()
{
cout << "Creating BaseVector" << endl;
}
virtual ~BaseVector()
{
cout << "Destructing BaseVector" << endl;
}
};
class FooVector : public BaseVector
{
public:
FooVector()
{
cout << "Creating FooVector" << endl;
}
virtual ~FooVector()
{
cout << "Destructing FooVector" << endl;
}
};
int main()
{
BaseVector* ptr = new FooVector();
ptr->push_back(Test(1));
delete ptr;
return 0;
}
This code gives following output:
Creating BaseVector
Creating FooVector
Creating Test 1
Creating copy of Test 1
Destructing Test 1
Destructing FooVector
Destructing BaseVector
Destructing Test 1