【发布时间】:2019-02-14 05:04:41
【问题描述】:
我正在构建一个由车辆、陈列室和经销商组成的项目。我已经构建了类,并且正在测试我的方法 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
有人知道为什么这个析构函数会弄乱我的输出吗?
【问题讨论】:
-
尝试使用 unique_ptr。如果一切正常,那么您的原始代码中可能会出现重复删除或类似错误(在复制构造函数中只是传递 ptr 但仍在新的复制析构函数中将其删除)。
-
我建议生成minimal reproducible example。如果这没有向您显示问题并允许您修复它,请在此处发布 MCVE。现在有很多事情可能发生,你必须缩小范围。
-
@huseyintugrulbuyukisik 我在我的复制构造函数中做了一个 showroomList 的深层复制
-
@Pablo 你通过一些检查来禁止它的双重删除?
-
用 XY 解决方案看这个,你可以用
std::vector<Showroom> showroomList替换Showroom* showroomList吗?如果没有别的vectors Rule of Five 合规性应该消除许多可能的问题,at方法将有助于检测越界访问。
标签: c++ pointers destructor