Problem of removal of the facility by reference class indicator



  • I'll just go for example:

    class B {
        int k{};
       //... НЕТ виртального деструктора
    };
    

    class D : public B {
    int n{1};
    //...
    };
    void foo(B* pb)
    {
    //...
    pb = new D;
    //...
    delete pb;
    }

    Could there be a problem with functions? If so, why or what is the standard in this regard (what is meant for simple types)? ♪



  • The standard makes no difference between simple and complex types. Removing the heir through a parent ' s index without a virtual destructator is always an uncertain behaviour.

    http://eel.is/c++draft/expr.delete#3

    In a single-object delete expression, if the static type of the object to be deleted is not similar ([conv.qual]) to its dynamic type and the selectedlocation function (see below) is not a destroying operator delete, the static type deal shall be a base class of the dynamic type of the object to be deleted and the static type shall have a virtual destructor or the behavior is undefined.

    Free translation: if delete to type-indicator A *which actually points to a type object BB must be the heir. Aand A There must be a virtual destructor, otherwise the conduct is not defined.


    In practice, yes, if B doesn't add new fields with empty depravers, nothing should break.

    But you can say the edge if a copy of the parent is not at the very beginning of the descendant, but somewhere in the middle (because there's another parent in front of him or an index to the virtual table). As a result, to a memory-free function (operator delete()The wrong address.

    struct A {int x;};
    struct C : A {virtual void foo() {}};
    

    int main()
    {
    A *a = new C;
    delete a;
    }

    struct A {int x;};
    struct B {int y;};
    struct C : A, B {};

    int main()
    {
    B *b = new C;
    delete b;
    }

    struct A {int x;};
    struct C : virtual A {};

    int main()
    {
    A *a = new C;
    delete a;
    }


Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2