Menu

False positive: [danglingTemporaryLifetime]

2020-07-17
2020-09-10
  • Andreas Grob

    Andreas Grob - 2020-07-17
    #include <map>
    
    struct A {
        std::map<int, int> m{{1, 1}, {2, 2}, {3, 3}};
    };
    
    struct Base {
        virtual auto get() -> A & = 0;
    };
    
    struct B : public Base {
        A a{};
        auto get() -> A & override { return a; }
    };
    
    int main() {
        B b;
        A &a = b.get();
        auto it = a.m.find(2);
    }
    

    cppcheck: commit 62702a6
    built with: make MATCHCOMPILER=yes FILESDIR=/usr/share/cppcheck HAVE_RULES=yes

    $ cppcheck  main.cpp
    Checking main.cpp ...
    main.cpp:19:13: error: Using iterator to local container 'm' to temporary. [danglingTemporaryLifetime]                                                                                        
        auto it = a.m.find(2);
                ^
    main.cpp:19:16: note: Iterator to container is created here.
        auto it = a.m.find(2);
                   ^
    main.cpp:4:24: note: Variable created here.
        std::map<int, int> m{{1, 1}, {2, 2}, {3, 3}};
                           ^
    main.cpp:19:13: note: Using iterator to local container 'm' to temporary.
        auto it = a.m.find(2);
                ^
    

    The error disappears if you remove the Base struct, it also goes away if you just remove the override keyword. P.ossibly related to False positive: [returnTempReference]

     

    Last edit: Andreas Grob 2020-07-17
  • Daniel Marjamäki

    Thanks! I have created ticket https://trac.cppcheck.net/ticket/9813

     
  • Andreas Grob

    Andreas Grob - 2020-09-10

    Fixed for me in 48a6852.

     

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.