我正在构建一个由车辆、陈列室和经销商组成的项目。我已经构建了这些类,我正在测试我的方法 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] 删除。
我来说两句