`assert` in循环

aia*_*iao 4 c++ optimization assert loops

for(unsigned int i = 0; i < x.size(); i++)
    assert(x[i] > 0);
Run Code Online (Sandbox Code Playgroud)

不调试(NDEBUG标志)时,结果是空for循环.是否有一种干净的方法来处理这个问题(不执行空for循环); 最好没有预处理器指令,因为它首先会破坏目的assert.

Fre*_*Foo 6

inline bool all_positive(std::vector<int> const &x)
{
    for (size_t i = 0; i < x.size(); i++)
        if (x[i] <= 0)
            return false;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

然后

assert(all_positive(x));
Run Code Online (Sandbox Code Playgroud)

(虽然这可能会在NDEBUG定义时为您提供"未使用的功能"警告).


NPE*_*NPE 5

一个好的优化器应该能够在NDEBUG定义时消除整个循环(我刚刚测试了我的,它确实做到了)。

或者,您可以用#ifndef NDEBUG/包围整个循环#endif。你说这“首先会破坏目的assert”,但我并没有真正遵循推理。