0

It is mentioned in Scott Meyer's book that part of the overhead caused by using shared pointers is that they need virutal function to destroy the pointed object correctly. My question is why? Is this not supposed to be the responsibility of the class of that pointed object to have a virtual destructor?

mkmostafa
  • 3,071
  • 2
  • 18
  • 47

1 Answers1

1

Is this not supposed to be the reponsibility of the class of that pointed object to have a virtual destructor?

That would be one possible way to design a shared pointer, but std::shared_ptr allows you to do the following, even if Base does not have a virtual destructor:

std::shared_ptr<Base> p { new Derived{} };

It does this by capturing the correct deleter for the argument when the std::shared_ptr is constructed, then calls that when the reference count hits zero rather than just using delete (of course, you can pass your own custom deleter to use instead). This is commonly referred to as type erasure, and this technique is generally implemented using virtual function calls.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • so it's some kind of flexibility. One follow up question. here http://stackoverflow.com/questions/3899790/shared-ptr-magic it is mentioned in the solution that the type can be deduced by using a templated constructor and using template type deduction on construction. would not that solution eliminate the overhead of virtual functions? – mkmostafa Oct 20 '16 at 11:07
  • @mkmostafa You still need to store and call the deleter somehow though. – TartanLlama Oct 20 '16 at 11:10
  • but you can store a pointer to the destructor of the deduced type and call it directly. I mean in this case store a pointer to ~Derived not Base when the shared pointer is constructed? – mkmostafa Oct 20 '16 at 11:11
  • 1
    @mkmostafa For something like that you'd need the type of the deleter to be a template parameter to `std::shared_ptr`, like it is for `std::unique_ptr`, rather than something deduced in the constructor. – TartanLlama Oct 20 '16 at 11:13
  • 1
    I think i got it now :) this is because you would need a member deleter that depends on a different type from that of the shared pointer? – mkmostafa Oct 20 '16 at 11:16
  • 1
    @mkmostafa Exactly :D – TartanLlama Oct 20 '16 at 11:18