Menu

invalidContainerReference false positive

Cyphall
2025-07-12
2025-07-14
  • Cyphall

    Cyphall - 2025-07-12

    Using emplace_back on a vector may indeed invalidate references to existing objects, but not to the emplaced object itself.

    Sample code:

    #include <vector>
    #include <memory>
    
    struct Value
    {
        int data;
    };
    
    int main()
    {
        std::vector<std::unique_ptr<Value>> values;
    
        for (int i = 0; i < 5; i++)
        {
            std::unique_ptr<Value>& value = values.emplace_back(std::make_unique<Value>(i));
            value->data = 5;
        }
    
        return 0;
    }
    

    cppcheck error (file paths were removed):

    error: Reference to values that may be invalid. [invalidContainerReference]
      value->data = 5;
      ^
    note: Assigned to reference.
      std::unique_ptr<Value>& value = values.emplace_back(std::make_unique<Value>(i));
                                    ^
    note: Accessing container.
      std::unique_ptr<Value>& value = values.emplace_back(std::make_unique<Value>(i));
                                             ^
    note: Assuming condition is true.
     for (int i = 0; i < 5; i++)
                       ^
    note: After calling 'emplace_back', iterators or references to the container's data may be invalid .
      std::unique_ptr<Value>& value = values.emplace_back(std::make_unique<Value>(i));
                                             ^
    note: Reference to values that may be invalid.
      value->data = 5;
      ^
    
     

    Last edit: Cyphall 2025-07-12
  • CHR

    CHR - 2025-07-14

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/14013

     

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.