为什么指针增量语句被优化了?

Cod*_*ero 1 c++ embedded optimization

我已经编写了一种方法来解析GPS中的字符串,但出于某种原因,关键线在不使用时会被优化掉-O0.方法代码如下:

bool Gps::ParsePMTK_ACK(PmtkAck_t &dst, uint8_t *buf, int32_t size)
{    
    // Verify message ID
    uint8_t *pCur = buf;

    memset(&dst, 0, sizeof(dst));

    if (strncmp((char*)pCur, "$PMTK001", 8) != 0) {
        return false;
    }

    pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
                     //      thus causing the pointer to NOT be incremented

    if (*pCur != SEPARATOR) {
        return false;
    }

    ++pCur; // <--- Not optimized away

    if (ProcessInt(dst.cmd, &pCur) != 1) {
        return false;
    }

    int16_t tmp;

    if (ProcessInt(tmp, &pCur) != 1) {
        return false;
    }

    dst.flag = static_cast<AckFlag_t>(tmp);

    return true;
} // end ParsePMTK_ACK
Run Code Online (Sandbox Code Playgroud)

删除此行时,函数无法处理格式正确的消息,因为pCur==bufif (*pCur != SEPARATOR)条件下.因此,该函数返回false一个格式良好的消息,因为当达到if语句时,指针指向错误的字符.

为什么指示的行完全被优化器删除?有没有更好的方法来实现,以便我实现所需的行为(即,一个递增的指针),即使启用了优化器?

Jab*_*cky 8

我想编译器会转换原始代码:

pCur = pCur + 8; // <--- This line gets optimized away when not on -O0
                 //      thus causing the pointer to NOT be incremented

if (*pCur != SEPARATOR) {
    return false;
}

++pCur; // <--- Not optimized away
Run Code Online (Sandbox Code Playgroud)

进入这样的事情:

if (*(pCur + 8) != SEPARATOR) {
    return false;
}

pCur += 9;
Run Code Online (Sandbox Code Playgroud)

因此在调试时会引起混淆.