Why don't STL containers have virtual destructors?

后端 未结 9 2195
时光取名叫无心
时光取名叫无心 2020-11-28 07:54

Does anyone know why the STL containers don\'t have virtual destructors?

As far as I can tell, the only benefits are:

  • it reduces the size of an insta
9条回答
  •  醉梦人生
    2020-11-28 08:13

    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
    

提交回复
热议问题