Effective C + + clause 7 declaring a virtual destructor for a polymorphic base class

Source: Internet
Author: User

1. If a class is going to be a base class, it should have a virtual destructor to prevent the "partial destruction" problem that occurs when the delete is directed to a derived class object by a base-class pointer, avoiding memory leaks, corrupted data structures, wasting time on the debugger, and so on; Any class with a virtual function almost certainly needs a virtual destructor.

2. The member function should not be set to a virtual function if it is not required, otherwise, if a class that does not have a virtual function has a virtual function, it will add an implied vptr (virtual table pointer) pointer (to the virtual function table to support dynamic binding), in which case , the "volume" of the class increases, not only because of the increased level of indirection reduces efficiency, but also may be due to the increase in volume caused it can not be put into the buffer cache, and so on.

3. It is best not to inherit classes that do not have virtual destructors (for reasons 1), including all STL containers, and not all base classes are designed for polymorphic purposes.

4. You can make a class with a pure virtual function as an abstract base class, but you must give the destructor a definition (because the invocation of a derived class destructor inevitably leads to the invocation of the base class destructor).

Effective C + + clause 7 declaring a virtual destructor for a polymorphic base class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.