【问题标题】:Deallocating an array causes an exit 11 code [closed]释放数组会导致退出 11 代码 [关闭]
【发布时间】: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&lt;Showroom&gt; showroomList 替换 Showroom* showroomList 吗?如果没有别的vectors Rule of Five 合规性应该消除许多可能的问题,at 方法将有助于检测越界访问。

标签: c++ pointers destructor


【解决方案1】:

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

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;}) 作为其第二个构造函数参数。

至少这样你就可以知道错误是否与new和delete有关。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多