PDA

View Full Version : app crashes again



sophister
15th June 2009, 08:08
Hi again, I'm faced with the second application's crash.
Here is my code:

void DishManager::initPage1()
{
ui.p1FamilyComboBox->addItems(dishes->getFamilies());
}
where p1FamilyComboBox is a instance of
QComboBox, and dishes is an instance of the following class Record.


const QStringList& Record::getDishNamesByFamily(const QString &family) const
{
QStringList names;
for(int i = 0; i < dishes.size(); i++)
{
if(dishes[i].getFamily() == family)
{
names << dishes[i].getName(); //如果某菜谱属于此菜系,则加入其菜名
}
}
return names;
}I think maybe it's due to the
const QStringList& Record::getDishNamesByFamily
Is there anything wrong with the returning value.
Thanks in advance!!

nish
15th June 2009, 08:14
change



const QStringList& Record::getDishNamesByFamily()

to


QStringList Record::getDishNamesByFamily()


阅读有关悬挂指针(引用)

sophister
15th June 2009, 09:27
Oh, thank you!!
You know Chinese Simplified!!(简体中文).
But I do not realize it would be something with the reference or pointer. C++ is really strange!

nish
15th June 2009, 09:49
it is very simple...

the local var
QStringList names;
is destroyed when the function returns... so the pointer(reference) to it(the return type) is pointing to the
illegal memory hence the crash..


Btw .. i just used google translater to translate..:) i dont know chinese no matter how simplified it is...

sophister
15th June 2009, 09:54
Oh, I see.
Thanks very much!!!

sophister
15th June 2009, 10:20
The following codes have any problem??

const QString& getName() const {return name;}
it is a method of class Dish. name is a member variable of class Dish.
When I do the following, it crashes again:

label.setText(dish.getName());

Is this the same problem as above?
Thanks!!

nish
15th June 2009, 10:28
it should not crash now... can u write a minimal compilable example reproducing the problem?

sophister
15th June 2009, 11:01
thanks.
I have modify my codes.
I remember that it is said in the <Thinking in C++>, that reference is only to be used in function variables. Maybe I overuserd it.