gpt4 book ai didi

C++ : List Seg Fault

转载 作者:行者123 更新时间:2023-11-28 06:13:09 26 4
gpt4 key购买 nike

谁能解释一下为什么会这样?

当我在 if-else block 内调用成员函数 printEvent() 时,我得到了正确的输出,但是当我在该 block 之后调用 printEvent() 时,我得到了这个未知结果。

        list<Event*> currentEvents;
for (j=1; j <= eventsNum; ++j)
{
Event * newEvent;

if (isIndividual(inFile)) {
IndividualEvent newIndi = returnIndi(inFile);
newEvent = &(newIndi);
newEvent->printEvent();
}else {
TeamEvent newTeam = returnTeam(inFile);
newEvent = &(newTeam);
newEvent->printEvent();
}
cout << "WHY?" << endl;
newEvent->printEvent();


currentEvents.push_back(newEvent);
}
TVNode.push_back(newEmission);
}

输出

<Filiko1>
WHY HERE?
<Filiko1q<15-06-2015,14:00<Athens<0`W ����Athensq<Football<1<0>!0����Footballq<2q<Olympiakos<PSG!
����OlympiakosxW^��DW����PSG^��DWPW�^��DWi�n

以上代码是一个大练习的一部分!

最佳答案

if 或 else block 之后的 newEvent 指向已经销毁的对象,因为对象的生命周期受其定义范围的限制。在您的情况下,对象 newIndinewTeam 将在 if-else 语句后被销毁,而 newEvent 指针仍指向其中之一。

请参阅此链接了解 C++ 作用域:http://en.cppreference.com/w/cpp/language/scope

关于C++ : List Seg Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com