zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    [linux]无法加载so文件错误
    linux找不到.so文件的解决方法
    [Linux]core文件调试方法
    LINUX下cp f无效问题
    解决IE无法查看源文件问题
    批处理获取exe返回结果
    不得不知 云计算入门必备的60条术语
    NMS
    开启和关闭(禁用)IE8加速器功能的办法
    钩子函数
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15192660.html
Copyright © 2011-2022 走看看