2

Do we need to define a destructor if the class has an std::vector in it?

If I define empty virtual destructors for both the based class and the derived class, will I get memory leak?

class fruit{
    public:
        uint32_t num_seed;
        //virtual ~fruit(void){}
} ;

class spiky_apple: public fruit{
    typedef std::vector<uint32_t> vector;

    public:
        vector spikes;
        void bomb(void);
            //spikes.reserve(2000)
            //and then spikes[i] = xyz.
        //virtual ~spiky_apple(void){}
} ;
rxu
  • 1,369
  • 1
  • 11
  • 29
  • 4
    Nope, the compiler generated destructor will be sufficient in this case. – Cory Kramer Jul 01 '16 at 19:58
  • Maybe, but not for the `vector` in your question. – James Adkison Jul 01 '16 at 19:58
  • Somehow when I iterate over i, spikes[i] = xyz is slower than getting pointer to zeroth member first (say that is ptr), then does ptr[i] = xyz. With -O3 optimization by intel c compiler, the ratio is 3.5 seconds : 3 seconds. – rxu Jul 01 '16 at 20:02
  • great and wonderful. I was thinking if I would get bombed by memory leaks. – rxu Jul 01 '16 at 20:03
  • Yes! This is a polymorphic class and you need a virtual destructor in base class and it would be good to explicitly overide it and make it virtual in the derived class for extension otherwise the fruit destructor will be called instead of a spiky_apple destructor when deleting a base class pointer. No problem in this particular example but as your code grows it could easily become a defect. – T33C Jul 01 '16 at 20:06
  • I just read some so questions saying the default destructor is virtual. some so questions recommend adding an empty default destructor. http://stackoverflow.com/questions/827196/virtual-default-destructors-in-c I guess i will add virtual destructor to both the base and derived class. just in case. – rxu Jul 01 '16 at 20:10
  • No the default destructor is not virtual because there is an overhead of a vtable whenever you have a virtual function. Remember the ; after each class definition. – T33C Jul 01 '16 at 20:12
  • @T33C: There is no reason whatsoever to manually override a virtual destructor if you don't add any functionality. As long as the base classes destructor is virtual, the one automatically generated by the compiler will do just fine. – MikeMB Jul 01 '16 at 21:48
  • @MikeMB - thanks for the correction. I agree that the base virtual destructor is sufficient and my advice about requiring a virtual destructor in the derived class was wrong if the default destructor is sufficient. – T33C Jul 02 '16 at 10:33

1 Answers1

1

Unless your class dynamically instantiates it's members or opens/creates external resources, you don't need to explicitly declare destructor. The default one will do.

Mureinik
  • 297,002
  • 52
  • 306
  • 350