cppcheck 建议减少变量的范围,我应该这样做吗?

cppcheck suggests to reduce scope of variable, should I?

所以我有这样的东西

    int age;

    for (auto person : persons) {
        age = std::stoi(person[0]);

        /* Do other stuff with age in this loop*/
    }

除了样式之外,在循环内声明 int age = std::stoi(person[0]); 是否有任何性能优势?

由于您仅在 for 循环内使用了 age 变量,您可以缩小其范围并仅在 for 循环内声明它。这样,一旦您在循环中使用完变量,编译器就不必记住它。

只有当你打算在循环外使用它时,才应该在循环外声明它。

are there any performance benefits

由于 "as-if" rule,可以合理地假设在声明相同变量的两种等效方法之间没有性能 差异