Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用指针清除队列时Endlessloop_C++ - Fatal编程技术网

C++ 使用指针清除队列时Endlessloop

C++ 使用指针清除队列时Endlessloop,c++,C++,我有一个结构LastTimeOn,它的下一个指针指向同一个结构。我不想引入反向指针。我正在努力清理这个结构,你能帮我吗?打开泵可以多次打开,然后结构会像这个泵1->lastTimeOn->next->next->next那样增长。程序在无限循环REM2REM3REM4REM2REM3REM4等中运行: class Pump { public: LastTimeOn *lastTimeOn; Pump(); }; class LastTimeOn{ public: uns

我有一个结构LastTimeOn,它的下一个指针指向同一个结构。我不想引入反向指针。我正在努力清理这个结构,你能帮我吗?打开泵可以多次打开,然后结构会像这个泵1->lastTimeOn->next->next->next那样增长。程序在无限循环REM2REM3REM4REM2REM3REM4等中运行:

class Pump {
public:
    LastTimeOn *lastTimeOn;
    Pump();
};

class LastTimeOn{
public:
    unsigned int dayOfWeek;
    unsigned int hour;
    unsigned int minute;
    LastTimeOn(unsigned int minute1, unsigned int hour1, unsigned int dayOfWeek1);
    LastTimeOn *next;
};

void clearLastTimeOn(Pump *pump1) {
    Serial.print("REM1");
    while (pump1->lastTimeOn != NULL) {
        LastTimeOn *lastTimeOn = pump1->lastTimeOn;
        Serial.print("REM2");
        while (lastTimeOn->next != NULL) {
            Serial.print("REM3");

            lastTimeOn = lastTimeOn->next;

        }
        Serial.print("REM4");
        delete lastTimeOn;
        if (pump1->lastTimeOn->next == NULL){
            Serial.print("REM4a");
            delete pump1->lastTimeOn;
            pump1->lastTimeOn = NULL;
        }
    }
    Serial.print("REM5");
}
我创建如下新数据:

lastTimeOn->next = new LastTimeOn(minute, hour, dayOfWeek);

我有个简单的想法。。。将pump1->lastTimeOn传递给以下对象:

void clearLastTimeOn(LastTimeOn* lastTimeOn)
{
    while (lastTimeOn != nullptr)
    {
        LastTimeOn* current = lastTimeOn;
        lastTimeOn = lastTimeOn->next;
        delete current;
    }
}

然后将pump1->lastTimeOn设置为nullptr。

请提供一个。你能想象一下,身体上没有clearLastTimeOn吗?我只需要为引用的LastTimeOn结构实现清除方法。它属于泵结构,但没关系。我想你是在为arduino这样的公司写东西。所以我建议不要使用您标记为答案的方法:)。事实上,对于任何其他平台,这也不是一个好主意。。。用豪尔赫的答案代替。但这不是内存泄漏吗?对象泵1->lastTimeOn->next->next的作用是什么?最远的对象会从内存中删除吗?LastTimeOn的析构函数会处理这些获取堆栈溢出例外的方法。我不喜欢的是,如果从列表中删除一个项,最好记住在删除它之前将
next
设置为
nullptr
,或者干脆删除列表。可能是
std::unique\u ptr
的理想人选。
class LastTimeOn{
public:
    unsigned int dayOfWeek;
    unsigned int hour;
    unsigned int minute;
    LastTimeOn(unsigned int minute1, unsigned int hour1, unsigned int dayOfWeek1);
    LastTimeOn();
    LastTimeOn *next;
    ~LastTimeOn() { delete this->next; }
};

void clearLastTimeOn(Pump *pump1) {
    if (pump1)
       delete pump1->lastTimeOn;
}