取消分配数组会导致退出 11 代码
Deallocating an array causes an exit 11 code
我正在构建一个由 Vehicle、Showroom 和 Dealership 组成的项目。我已经构建了 类,并且正在测试我的方法 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: 793.60
这是我想要的预期输出,但我被告知我有内存泄漏并且必须包含一个析构函数来释放我的 *Showroom showroomList 指针(我初始化如下在经销商构造函数中):
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
}
但是你有一对新的和删除的,所以你应该只检查一次删除。这将需要 class(或其静态变量)之外的一些全局计数器,并且这可能不如智能指针可读。
如果您为此使用多线程,那么使用 shared_ptr 和自定义删除器 ([](T * ptr){delete [] ptr;}
) 作为其第二个构造函数参数可能会更好。
至少这样你可以知道错误是关于新建还是删除。
我正在构建一个由 Vehicle、Showroom 和 Dealership 组成的项目。我已经构建了 类,并且正在测试我的方法 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: 793.60
这是我想要的预期输出,但我被告知我有内存泄漏并且必须包含一个析构函数来释放我的 *Showroom showroomList 指针(我初始化如下在经销商构造函数中):
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
}
但是你有一对新的和删除的,所以你应该只检查一次删除。这将需要 class(或其静态变量)之外的一些全局计数器,并且这可能不如智能指针可读。
如果您为此使用多线程,那么使用 shared_ptr 和自定义删除器 ([](T * ptr){delete [] ptr;}
) 作为其第二个构造函数参数可能会更好。
至少这样你可以知道错误是关于新建还是删除。