我用值填充了列表。我正在尝试一一再次使用它们。
我试过
while (!config.empty())
,用完后把front()擦掉了。还是没明白哪里出了问题。
std::list<Object*> config;
填充的配置(
config.push_back()
之后):
config[0]:
int testnumber = 1;
string testname = "Test1"
config[1]:
int testnumber = 2;
string testname = "Test2";
config[2];
int testnumber = 3;
string testname = "Test3";
---------------------------------------------------------------------
Logic* pLogic;
Object* pObject = config.front(); // config[0]
if (pObject) // while(!config.empty()) -- tried here
{
// do something
pLogic = new Logic(pObject);
config.pop_front();
}
逻辑:
Object* m_pObject;
Logic::Logic(Object* pObject)
:m_pObject(pObject)
{}
// Accessed config in other functions with m_pObject
代码运行良好并获得输出。然而最终得到
ERROR: Debug assertion failed
Expression:cannot dereference end list iterator
在您的
while
循环(while (pObject)
)内,您没有更新(至少在您发布的代码中)指针“pObject”,因此它始终指向列表顶部开头的同一个旧对象。这个问题会使你的循环无限循环,因此只要列表中有更多对象要弹出,它就会工作。在导致程序崩溃的迭代中,它尝试从空列表中弹出一个元素,这就是 UB。
要解决此问题,您所要做的就是:
pObject = config.front()
行后:
config.pop_front();
我弄清楚了在哪里使用该条件。
这就是它的样子,
Logic* pLogic;
if(!config.empty())
{
Object* pObject = config.front(); // config[0]
if (pObject)
{
// do something
pLogic = new Logic(pObject);
}
config.pop_front();
}