取消分配数组会导致退出 11 代码

巴勃罗

我正在构建一个由车辆、陈列室和经销商组成的项目。我已经构建了这些类,我正在测试我的方法 GetAveragePrice()

float Dealership::GetAveragePrice()

这种方法工作得很好:

Dealership dealership("COP3503 Vehicle Emporium", 3);
dealership.AddShowroom(&showroom);
dealership.AddShowroom(&secondary);
dealership.AddShowroom(&third);

cout << "Using just the GetAveragePrice() function\n\n";

cout << "Average price of the cars in the dealership: $" << std::fixed << std::setprecision(2);
cout << dealership.GetAveragePrice();

输出将是

Using just the GetAveragePrice() function

Average price of the cars in the dealership: $27793.60

这是我想要的预期输出,但我被告知我有内存泄漏并且必须包含一个析构函数来释放我的 *Showroom showroomList指针(我在 Dealership 构造函数中将其初始化为以下内容):

this->showroomList = new Showroom[maxNumOfShowrooms];

所以我写我的析构函数如下:

Dealership::~Dealership()
{
    delete [] showroomList;
}

现在,没有任何内存泄漏,但我没有得到预期的输出和退出代码 11:

Using just the GetAveragePrice() function


Process finished with exit code 11

有谁知道为什么这个析构函数会弄乱我的输出?

侯赛因·图格鲁尔·布尤基西克

这个版本只会在最后一个实例的析构函数中删除一次。

std::unique_ptr<ShowRoom> Dealership::showroomList;

Dealership::Dealership(size_t maxNumOfShowrooms)
           :showroomList(std::unique_ptr<ShowRoom>(new Showroom[maxNumOfShowrooms]))
{

}

Dealership::~Dealership()
{
    // auto deleted here, with reverse order of initialization
}

但是你有一个新的和删除的对,所以你应该只检查一次删除。这将需要类(或其静态变量)之外的一些全局计数器,并且这可能不像智能指针那样可读。

如果您为此使用多个线程,那么使用 shared_ptr 和自定义删除器 ( [](T * ptr){delete [] ptr;}) 作为其第二个构造函数参数可能会更好

至少通过这种方式您可以知道错误是否与新建和删除有关。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

fseek 进程以退出代码 11 结束

退出代码为139的过程结束(信号11:SIGSEGV中断)

QNetworkAccessManager 进程以退出代码 139 结束(被信号 11 中断:SIGSEGV)

为什么停止并以退出代码11结束?

/ usr / bin / codesign失败,退出代码为11

遇到等于运算符的问题。以退出代码 11 结束

为什么我的 C++ 代码在使用堆栈时以退出代码 11 结束?

尝试运行我的代码时出现“退出并返回代码 -11(SIGSEGV)”

从pthread create返回的代码是11

使用C ++ 11复制代码

PyCharm 绘图问题“进程已完成,退出代码为 139(被信号 11:SIGSEGV 中断)”

Android Studio模拟器:进程结束,退出代码为139(被信号11:SIGSEGV中断)

节点js脚本崩溃:进程结束,退出代码为139(被信号11:SIGSEGV中断)

Xcode 11 beta 4错误:命令CompileSwiftSources失败,退出代码为非零

Android Studio模拟器:进程结束,退出代码为139(被信号11:SIGSEGV中断)

如何摆脱 Pychar+Django 中的“进程已完成退出代码 139(被信号 11:SIGSEGV 中断)”

Xcode 11 Beta 7命令PhaseScriptExecution失败,退出代码为非零([CP] Copy Pods Resources)

PyQt5 QThread 进程完成退出代码 139(被信号 11 中断:SIGSEGV)

Xcode:* / swiftc失败,退出代码为11,该怎么办?

为什么我会遇到细分错误:此代码中为11

YouTube 嵌入代码 Internet Explorer 11

Android SipManager收到错误代码-11

渲染脚本致命信号11(代码= 1)

IE 11中的Java代码“ for of”失败

循环浏览IE 11中的代码块

iOS 11 Beta-NSURLErrorDomain-代码:18446744073709550617

11ty 短代码输出菜单

导入zbar会导致python以退出代码139退出-在运行10.9的Mac上,这可能导致什么呢?

使用PhantomJS创建HighCharts grahps服务器端以用于PDF创建(PHP)-从PHP exec()退出代码为11;