c++ - 调试断言失败。表达式映射迭代器不可取消引用

标签 c++ windows pointers memory-management

我正在尝试通过迭代器删除对象,如下面的代码所示。该程序似乎在 ubuntu 上运行良好,但我现在在 visual studio 中,它抛出调试断言失败错误。表达式:映射/设置迭代器不可取消引用。

如有任何帮助,我们将不胜感激。

map<string, Booking*> bookings; // private variable

 /**
 * remove a booking from the passenger's booking map.
 * @param flightNumber string& - flight number of the booking to be removed.
 */
void Passenger::removeBooking(string& flightNumber)
{
    map<string, Booking*>::iterator it = bookings.find(flightNumber);
    bookings.erase(it);
    delete (*it).second; // <-- error occurs here
}

/**
 * add a booking to the passenger's booking map.
 * @param booking Booking& - the booking to be added.
 */
void Passenger::addBooking(Booking& booking)
{
    Booking* bookingPtr = new Booking(booking);
    bookings.insert(pair<string, Booking*>(booking.getFlightNumber(), bookingPtr));
}

/**
 * add a booking to the passenger's booking map.
 * @param flightNumber string& - flight number of the booking.
 * @param seat Seat::Type - seat type of the booking.
 * @param status Booking::Type - status of the booking.
 */
void Passenger::addBooking(string& flightNumber, Seat::Type seat, BookingStatus::Type status)
{
    Booking *bookingPtr = new Booking(flightNumber, seat, status);
    bookings.insert(pair<string, Booking*>(flightNumber, bookingPtr));
}

最佳答案

好的,现在代码已经完全从最初发布的代码改变...

错误很容易被发现。您正在从 map 中删除使迭代器无效的元素,然后您正在尝试使用该迭代器。在删除迭代器之前,您应该制作一份需要delete 的指针的临时拷贝,或者只是重新排列并先执行delete

另外,正如评论中所建议的,您需要确保 find 返回的迭代器是有效的,即不等于 end()

map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
    Booking* temp = it->second;
    bookings.erase(it);
    delete temp;
}

map<string, Booking*>::iterator it = bookings.find(flightNumber);
if (it != bookings.end())
{
    delete it->second;
    bookings.erase(it);
}

关于c++ - 调试断言失败。表达式映射迭代器不可取消引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532193/

相关文章:

c++ - 存储指向对象成员变量的指针

c++ - 使用 xlib 将图像加载到窗口中

c++ - 通过 std::bind 传递右值

python - 无法在 Windows 上通过 Python 生成 azure TTS

如果其指针已更改类型,是否可以释放内存?

c++ - 无效的空指针 - C++ - VS2010

c++ - Visual Studio 2012 编译时间慢

c++ - 使用原始数据将 QImage 转换为 cv::Mat

c++ - 仅当从我的程序打开 CMD 时出现奇怪的 CMD 错误

vba - MSDataShape 错误,升级到 Windows 10 功能更新 1809 时损坏