Menu

Is this a false positive?

2025-01-18
2025-01-19
  • Bart Vandewoestyne

    My colleagues and me are discussing a cppcheck error for some code for which I created the following trimmed down example:

    #include <memory>
    
    class Timer {};
    
    class Controller {
    public:
      explicit Controller(std::unique_ptr<Timer> timer)
          : mpTimer(std::move(timer)) {}
    
    private:
      std::unique_ptr<Timer> mpTimer;
    };
    
    class Test {
    protected:
      void createController() {
        std::unique_ptr<Timer> upTimer = std::make_unique<Timer>();
        pTimer = upTimer.get();
    
        upController = std::make_unique<Controller>(std::move(upTimer));
      }
    
    protected:
      std::unique_ptr<Controller> upController;
      Timer *pTimer;
    };
    
    int main() {}
    

    The cppcheck error that we get (using cppcheck 2.16.0) is:

    bvandewoestyne@BVANDEW-70TZQ73:~/Downloads/cppcheck-2.16.0$ ./cppcheck ../test.cpp 
    Checking ../test.cpp ...
    ../test.cpp:18:5: error: Non-local variable 'pTimer' will use pointer to local variable 'upTimer'. [danglingLifetime]
        pTimer = upTimer.get();
        ^
    ../test.cpp:18:25: note: Raw pointer to smart pointer created here.
        pTimer = upTimer.get();
                            ^
    ../test.cpp:17:28: note: Variable created here.
        std::unique_ptr<Timer> upTimer = std::make_unique<Timer>();
                               ^
    ../test.cpp:18:5: note: Non-local variable 'pTimer' will use pointer to local variable 'upTimer'.
        pTimer = upTimer.get();
        ^
    

    We are unsure whether this is actually a false positive or not. Our reasoning is as follows:

    The lifetime for pTimer (the raw pointer to the object managed by upTimer) is indeed longer than for upTimer (which gets destroyed when createController ends and this indeed could be a problem), but before that destruction happens, upTimer is already moved into the object managed by upController which has a larger lifetime than pTimer. Had that std::move not happened, then I agree that this is a real error. But isn't this a false positive knowing that the std::move happened?

     
  • CHR

    CHR - 2025-01-19

    Looks like a variation of this issue: https://trac.cppcheck.net/ticket/12794

     

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.