Effective C++ 笔记 —— Item 7: Declare destructors virtual in polymorphic base classes.

If a class does not contain virtual functions, that often indicates it is not meant to be used as a base class. When a class is not intended to be a base class, making the destructor virtual is usually a bad idea.

Consider a class for representing points in two-dimensional space:

class Point 
{ 
    // a 2D point
public:
    Point(int xCoord, int yCoord);
    ~Point();
private:
    int x, y;
};

What is important is that if the Point class contains a virtual function, objects of that type will increase in size.

  • On a 32-bit architecture, they’ll go from 64 bits (for the two ints) to 96 bits (for the ints plus the vptr);
  • on a 64-bit architecture, they may go from 64 to 128 bits, because pointers on such architectures are 64 bits in size.

Addition of a vptr to Point will thus increase its size by 50–100%! No longer can Point objects fit in a 64-bit register. Furthermore, Point objects in C++ can no longer look like the same structure declared in another language such as C, because their foreign language counterparts will lack the vptr. As a result, it is no longer possible to pass Points to and from functions written in other languages unless you explicitly compensate for the vptr, which is itself an implementation detail and hence unportable.

 

Sometimes, however, you have a class that you’d like to be abstract, but you don’t have any pure virtual functions. What to do?

Declare a pure virtual destructor in the class you want to be abstract.

class AWOV 
{ 
    // AWOV = “Abstract w/o Virtuals”
public:
    virtual ~AWOV() = 0; // declare pure virtual destructor
};

 

The rule for giving base classes virtual destructors applies only to polymorphic base classes — to base classes designed to allow the manipulation of derived class types through base class interfaces.

 

Things to Remember 

  • Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should have a virtual destructor.
  • Classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.

 

posted @ 2021-08-27 10:14  MyCPlusPlus  阅读(50)  评论(0编辑  收藏  举报