• 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.
  • 相关阅读:
    Codeforces Round #652 (Div. 2) A. FashionabLee(几何)
    轻量应用服务器如何通过修改apache配置文件实现非https的访问多域名到不同子目录程序?
    在Windows环境下使用hexo搭建博客以及部署到gitee / github
    使用WordPress搭建个人手机博客(阿里云)
    访问自己服务器的ip地址
    php环境无法上传文件的解决方法
    SSRF漏洞
    CSRF全家桶(含义,防御,攻击)
    JS实现HTML实体与字符的相互转换
    CentOS系统下载及应用部署
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15192660.html
Copyright © 2020-2023  润新知