Menu

Inconsistent constVariablePointer. Part 2

2 days ago
2 days ago
  • Nikita Leontiev

    Nikita Leontiev - 2 days ago

    cppcheck 2.20.0 doesn't generate constVariablePointer for the following code:

    #include <string>
    
    class Object
    {
    private:
        std::string m_str;
    public:
        Object() : m_str("str") {}
        const std::string& get_str() const { return m_str; }
    };
    
    char buffer[256];
    
    struct Item
    {
        char* m_buffer;
        Item() : m_buffer(buffer) {}
    };
    
    struct Wrapper
    {
        Item m_item;
    };
    
    Object* get_object()
    {
        static Object object;
        return &object;
    };
    
    int main()
    {
        Wrapper wrap;
        Item& item = wrap.m_item;
        Object* obj = get_object();
        strcpy(item.m_buffer, obj -> get_str().c_str());
        return 0;
    }
    

    obj can be pointer to const.
    If item is a const reference, then constVariablePointer is generated successfully:

    int main()
    {
        ...
        const Item& item = wrap.m_item;
        ...
    }
    
    test\main.cpp:35:10: style: Variable 'obj' can be declared as pointer to const [constVariablePointer]
     Object* obj = get_object();
             ^
    
     
  • CHR

    CHR - 2 days ago

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

     

Log in to post a comment.

MongoDB Logo MongoDB