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.
  • 相关阅读:
    struts2后台返回json到jsp页面
    潜搜索——搜索界的趋势
    pat1022__字符串查找
    PAT1055___排序神题
    Codeforces Round #205 (Div. 2)C 选取数列可以选择的数使总数最大——dp
    Codeforces Round #204 (Div. 2) C. Jeff and Rounding——数学规律
    队列模拟题——pat1026. Table Tennis
    骰子点数概率__dp
    PAT1034. Head of a Gang ——离散化+并查集
    回文字符串的变形——poj1159
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15192660.html
Copyright © 2011-2022 走看看