同一指针的不同值

gal*_*ize 1 c++ qt pointers

我拿了一个指针m_room(类ServicePage中的Room*m_room,其中up​​dateRoom和addService函数是)

void ServicePage::updateRoom(QString _text)
{
    m_room = m_reservation->findRoom(_text.toInt());
    qDebug()<<m_room;
    qDebug() << m_room->m_idRoom;
}
Run Code Online (Sandbox Code Playgroud)

Room *Reservation::findRoom(int _id)
{
    QVector<Room>::iterator iterator;
    for(iterator = mv_addRooms.begin(); iterator != mv_addRooms.end(); iterator++)
        if(iterator->m_idRoom == _id)
        {
            qDebug()<<_id;
            Room _temp = *iterator;
            return &_temp;
        }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

和qDebug之后的答案还可以,但是当我以后拿qDebug回答不同的功能时:

bool ServicePage::addService()
{
    qDebug()<<m_room;
    qDebug()<<m_room ->m_idRoom;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

m_room与之前相同,但m_room-> m_idRoom返回不同的值(随机值),为什么会这样?

谢谢你的任何建议.

jxh*_*jxh 6

In findRoom(), you are returning a pointer to a variable allocated on the stack.

        qDebug()<<_id;
        Room _temp = *iterator;
        return &_temp;
Run Code Online (Sandbox Code Playgroud)

The memory pointed to by the return value of findRoom() is no longer valid when the function returns.

您可以通过简单地获取解除引用的迭代器的地址来解决此问题:

        qDebug()<<_id;
        return &*iterator;
Run Code Online (Sandbox Code Playgroud)

这样,您将返回指向容器中实例的指针.如果你的容器是一个小心,要小心vector<>.如果vector<>增大,则之前返回的所有指针值现在都无效.