Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Virtual functions are "costly" too, but C++ has them and it's considered poor form to not declare your destructor virtual.

It's a bit more subtle than that: a virtual destructor is only required when the class, or its base classes, already have another virtual function (and it's only really needed if another class inherits from it. hmm.) At that point, a virtual destructor doesn't add any more cost over and above the virtual function that's already defined.



But not putting one, using foreign code base might get you in trouble (resource leaking, not de-initializing certain piece of the parent, threads not closing, etc.).

This would've been prevented if destructors were always virtual.

My take is that if the compiler cannot make the decision, but it's left to you, in this case it's better to always have the virtual destructors ON.

The problem is more visual than analytical - you would have to dig through the whole hierarchy in several files to understand whether you need to put a virtual destructor or not. Compiler/Linker/some post-proc tool should be better at that job. It already has all that information.


Hm, I'd rather pay the cost of having to add a virtual keyword in a few places (easily found using the equivalent of g++ -Wnon-virtual-dtor, and you do ship C++ code that is warning-free, right? :) rather than have to deal with up to eight bytes extra per instance in all my classes.


Thanks for the hint!

Actually I did not know about this option. I've just fixed such bug in one of our tools, written using wxWidgets for Windows. Have to check MSVC on this option.

At the same time a coworker was able to get the Xbox360 analyze thing and it worked finding suspicious stuff in the runtime code.

But we have only the professional version for PC :(



> a virtual destructor is only required when the class, or its base classes, already have another virtual function

Your derived class only needs a virtual destructor if the base class's destructor is public. If the base class destructor is protected (or private), then no one can call delete on a pointer to a base class.


This is why I rather enjoy discussing horrible hairy corner cases like this - there's always something I've overlooked :)


(little nitpicking note : there are cases where it can be useful to have a virtual descriptor as the only virtual method of a class)


I'm interested in knowing what these are - barring an alignment-related weirdness, I can't think of any reason to do that.


If you do everything in the constructor and the destructor, and in the meantime store a generic instance (or maybe a list of generic instances) somewhere.

This can be a quite rare situation, though. But not impossible.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: