From a5f577d179e09e436b544bcbbb6b798a47f6c8b6 Mon Sep 17 00:00:00 2001 From: PKEuS Date: Mon, 26 Oct 2015 18:47:44 +0100 Subject: [PATCH] Support range-based for-loop in CheckClass::checkConst() (#5514) --- lib/checkclass.cpp | 4 ++++ test/testclass.cpp | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 87c97521e..6bf432150 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -1868,6 +1868,10 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Function *func, bool& if (lhs->previous()->variable()->typeStartToken()->strAt(-1) != "const" && lhs->previous()->variable()->isPointer()) return false; } + } else if (lhs->str() == ":" && lhs->astParent() && lhs->astParent()->str() == "(" && tok1->strAt(1) == ")") { // range-based for-loop (C++11) + // TODO: We could additionally check what is done with the elements to avoid false negatives. Here we just rely on "const" keyword being used. + if (lhs->astParent()->strAt(1) != "const") + return false; } else { const Variable* v2 = lhs->previous()->variable(); if (lhs->tokType() == Token::eAssignmentOp && v2) diff --git a/test/testclass.cpp b/test/testclass.cpp index 4886371f5..c68efaf4a 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -170,6 +170,7 @@ private: TEST_CASE(constFriend); // ticket #1921 - fp for friend function TEST_CASE(constUnion); // ticket #2111 - fp when there is a union TEST_CASE(constArrayOperator); // #4406 + TEST_CASE(constRangeBasedFor); // #5514 TEST_CASE(initializerListOrder); TEST_CASE(initializerListUsage); @@ -5780,6 +5781,22 @@ private: ASSERT_EQUALS("[test.cpp:10]: (style, inconclusive) Technically the member function 'foo::c' can be const.\n", errout.str()); } + void constRangeBasedFor() { // #5514 + checkConst("class Fred {\n" + " int array[256];\n" + "public:\n" + " void f1() {\n" + " for (auto & e : array)\n" + " foo(e);\n" + " }\n" + " void f2() {\n" + " for (const auto & e : array)\n" + " foo(e);\n" + " }\n" + "};"); + ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'Fred::f2' can be const.\n", errout.str()); + } + void checkInitializerListOrder(const char code[]) { // Clear the error log errout.str("");