简体   繁体   中英

Is this undefined behavior or not?

class A
{
public:
    int i;
    ~A()
    {   
        std::cout << "~A" << std::endl;
    }   
};

class B: public A
{
public:
    int k;
    ~B()
    {   
        std::cout << "~B" << std::endl;
    }   
};

int main(int argc, char* argv[])
{
    A* p = new B();
    delete p;
    return 0;
}

The above doesn't cause memory leak though base destructor is not virtual and I know the reason.

But is this undefined behavior or not?

Say there won't be memory leak if derived class doesn't point to other dynamic data even though base destructor is non-virtual?

Yes it is . Deleting an object of a derived class through a pointer to a base class with no virtual destructor is textbook UB.

5.3.5/3:

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73)

Because it's undefined behavior, it doesn't really make sense to guess whether the code will leak or not. Just attempt to fix the code instead of predicting results.

Yes, since the static type (here it's A ) differs from the dynamic type ( B in your example) and there's no virtual destructor, it's an UB.

5.3.5/2 (5.3.5/3 in C++11):

In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM