繁体   English   中英

调试断言失败。 Expression Map迭代器不可取消

[英]Debug Assertion Failed. Expression Map iterator not dereferencable

我正在尝试通过迭代器删除对象,如下面的代码所示。 该程序似乎可以在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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM