Menu

2.10 FP constVariable

2023-03-15
2023-03-16
  • Josh Harmon

    Josh Harmon - 2023-03-15

    Cppcheck's suggestion to make ptr const in the below code seems problematic given that the return type is non-const and compilers find such a change rather unamusing. (godbolt)

    file.cpp:21:16: style: Variable 'ptr' can be declared as pointer to const [constVariable] for (auto* ptr : ptrs)

    Below is a copy of the working version of the godbolt (cppcheck --enable=all --std=c++20 --platform=win64 .\file.cpp):

    #include <iostream>
    
    struct I {
        virtual int A() const = 0;
    };
    
    class C : public I {
    public:
        explicit C(int m_) : m(m_) {};
        int A() const override { return m; };
    private:
        int m{};
    };
    
    C cs[] = {C{1}, C{2}, C{3}};
    
    C* ptrs[] = {cs, cs+1, cs+2};
    
    I* getThing()
    {
        for (auto* ptr : ptrs)
        {
            std::cout << ptr->A() << '\n';
            if ( ptr->A() == 2)
                return ptr;
        }
        return nullptr;
    }
    
    int main()
    {
        I* theThing2 = getThing();
        std::cout << theThing2 << '\n';
        return 0;
    }
    
     
  • CHR

    CHR - 2023-03-16

    No repro with head, so it seems to have been fixed already.

     

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.