Menu

False Positive danglingTempReference

2023-11-11
2023-11-11
  • Stefan van Kessel

    #include <string>
    int main() {
      std::string str;
      for (auto &cstr : {"Hello", "World", "!"}) {
        str += cstr;
      }
      return str.length();
    }
    

    causes

    PS D:\tmp\cppcheck> .\bin\cppcheck.exe D:\tmp\test.cpp --enable=style
    Checking D:\tmp\test.cpp ...
    D:\tmp\test.cpp:5:12: error: Using reference to dangling temporary. [danglingTempReference]
        str += cstr;
               ^
    

    which I believe to be a false positive. I don't think cstr is dangling at the point of use. The lifetime of the initializer list gets extended for the entire range based for loop.
    If I make it const auto& cstrI cease getting the error but the deduced type is const char* const either way.
    https://cppinsights.io/s/7682d5d4

    This is related to https://github.com/danmar/cppcheck/commit/a57fc9ace6f288b9c887d4ac6a24444cdceccd83

     
  • CHR

    CHR - 2023-11-11

    See https://trac.cppcheck.net/ticket/12173
    If you go through this process: https://trac.cppcheck.net/ you can get your own trac account 😉

     
  • Stefan van Kessel

    Thank you Christian for not only adding the issue but already having fixed it!

    I'll go ahead and request an trac account.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.