gpt4 book ai didi

c++ - 虚拟机段错误

转载 作者:太空狗 更新时间:2023-10-29 23:33:56 27 4
gpt4 key购买 nike

我有以下 C++ 代码:

#include <iostream> 

class Number
{
public:
virtual void foo(){std::cout << "Number foo\n";};
Number (){ std::cout << "Number ctor" << std::endl;}
virtual ~Number(){ std::cout << "Number dtor" << std::endl;}
};


class Complex : public Number
{
public:
virtual void foo(){std::cout << "Complex foo\n";};
Complex (double r=0, double i=0) : _r (r), _i (i)
{ std::cout << "Complex ctor" << std::endl; };
virtual ~Complex(){ std::cout << "Complex dtor" << std::endl;}
private:
double _r,_i;
};


int main()
{
Number *numArr = new Complex [2];
delete [] numArr;
return 0;
}

当析构函数被声明为虚拟时,应用程序将退出并出现段错误。当它未声明为虚拟时,将调用 Number 类析构函数(这很明显......)。但是,当析构函数被声明为虚拟时,并且当我删除 Complex 类中的 double 时,没有段错误并且析构函数按预期顺序调用(Complex,Number),所以我猜问题是相关的关于物体的大小,谁能给我解释一下?谢谢,阿米特。

最佳答案

Number *numArr = new Complex [2];
delete [] numArr;

实际上,删除操作会调用未定义的行为。

§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.)

它的实际意思是这样的:

Number *object= new Complex();
delete object; //well-defined

//BUT
Number *array = new Complex[N];
delete [] array; //undefined

关于c++ - 虚拟机段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7547538/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com