diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 77a21e8f7..9bacbb615 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -1539,12 +1539,22 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Token *tok) // increment/decrement (member variable?).. else if (Token::Match(tok1, "++|--")) { + // var++ and var-- if (Token::Match(tok1->previous(), "%var%") && tok1->previous()->str() != "return") { if (isMemberVar(scope, tok1->previous())) isconst = false; } + + // var[...]++ and var[...]-- + else if (tok1->previous()->str() == "]") + { + if (isMemberVar(scope, tok1->previous()->link()->previous())) + isconst = false; + } + + // ++var and --var else if (Token::Match(tok1->next(), "%var%")) { if (isMemberVar(scope, tok1->next())) diff --git a/test/testclass.cpp b/test/testclass.cpp index a24e337a2..36cfd0069 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -176,6 +176,7 @@ private: TEST_CASE(constoperator3); TEST_CASE(constoperator4); TEST_CASE(constincdec); // increment/decrement => non-const + TEST_CASE(constincdecarray); // increment/decrement array element => non-const TEST_CASE(constReturnReference); TEST_CASE(constDelete); // delete member variable => not const TEST_CASE(constLPVOID); // a function that returns LPVOID can't be const @@ -5400,6 +5401,34 @@ private: ASSERT_EQUALS("", errout.str()); } + // increment/decrement array element => not const + void constincdecarray() + { + checkConst("class Fred {\n" + " int a[2];\n" + " void nextA() { return ++a[0]; }\n" + "};\n"); + ASSERT_EQUALS("", errout.str()); + + checkConst("class Fred {\n" + " int a[2];\n" + " void nextA() { return --a[0]; }\n" + "};\n"); + ASSERT_EQUALS("", errout.str()); + + checkConst("class Fred {\n" + " int a[2];\n" + " void nextA() { return a[0]++; }\n" + "};\n"); + ASSERT_EQUALS("", errout.str()); + + checkConst("class Fred {\n" + " int a[2];\n" + " void nextA() { return a[0]--; }\n" + "};\n"); + ASSERT_EQUALS("", errout.str()); + } + // return pointer/reference => not const void constReturnReference() {