Why don't STL containers have virtual destructors?

后端 未结 9 2198
时光取名叫无心
时光取名叫无心 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:17

    Another solution to be able to subclass from STL containers is one given by Bo Qian using smart pointers.

    Advanced C++: Virtual Destructor and Smart Destructor

    class Dog {
    public:
       ~Dog() {cout << "Dog is destroyed"; }
    };
    
    class Yellowdog : public Dog {
    public:
       ~Yellowdog() {cout << "Yellow dog destroyed." << endl; }
    };
    
    
    class DogFactory {
    public:
       static shared_ptr createYellowDog() { 
          return shared_ptr(new Yellowdog()); 
       }    
    };
    
    int main() {
        shared_ptr pd = DogFactory::createYellowDog();
    
        return 0;
    }
    

    This avoids the dillema with virtual destructors altogether.

提交回复
热议问题