调试断言失败。表达式映射迭代器不可解除引用

时间:2013-12-11 23:35:45

标签: c++ windows pointers memory-management

我正在尝试通过迭代器删除对象,如下面的代码所示。该程序似乎在ubuntu上正常运行,但我现在在visual studio中,它正在抛出一个调试断言失败错误。表达式:Map / set iterator not dereferencable。

非常感谢任何帮助。

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));
}

1 个答案:

答案 0 :(得分:1)

好了,现在代码完全从最初发布的内容改变了

错误很容易发现。你正在擦除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);
}