From a0d8f44603c76f4a798afe40d5b7d6adc7b43aca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 23 Jan 2010 22:36:04 +0100 Subject: [PATCH] CheckClass: The operator< etc member functions can often be const --- lib/checkclass.cpp | 17 +++++++++++------ test/testclass.cpp | 11 +++++++++++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index e6d79497e..784ccfc8d 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -1406,7 +1406,7 @@ void CheckClass::checkConst() for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if (Token::Match(tok, "class %var% :|{")) + if (Token::Match(tok, "class|struct %var% :|{")) { // get class name.. const std::string classname(tok->strAt(1)); @@ -1426,19 +1426,24 @@ void CheckClass::checkConst() break; // member function? - if (Token::Match(tok2, "[;}] %type% %var% (")) + if (Token::Match(tok2, "[;}] %type% %var% (") || + Token::Match(tok2, "[;}] %type% operator %any% (")) { + // goto function name.. + while (tok2->next()->str() != "(") + tok2 = tok2->next(); + // get function name - const std::string functionName(tok2->strAt(2)); + const std::string functionName((tok2->isName() ? "" : "operator") + tok2->str()); if (functionName == classname) continue; // goto the ')' - tok2 = tok2->tokAt(3)->link(); + tok2 = tok2->next()->link(); if (!tok2) break; - // is this function implemented inline? + // is this a non-const function that is implemented inline? if (Token::simpleMatch(tok2, ") {")) { // if the function doesn't have any assignment nor function call, @@ -1466,7 +1471,7 @@ void CheckClass::checkConst() } // function call.. - else if (Token::Match(tok3, "%var% (")) + else if (tok3->str() != "return" && Token::Match(tok3, "%var% (")) { isconst = false; break; diff --git a/test/testclass.cpp b/test/testclass.cpp index 0980335ec..425f96737 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -81,6 +81,7 @@ private: // can member function be made const TEST_CASE(const1); + TEST_CASE(const2); } // Check the operator Equal @@ -1555,6 +1556,16 @@ private: "};\n"); ASSERT_EQUALS("", errout.str()); } + + // operator< can often be const + void const2() + { + checkConst("struct Fred {\n" + " int a;\n" + " bool operator<(const Fred &f) { return (a < f.a); }\n" + "};\n"); + ASSERT_EQUALS("[test.cpp:3]: (style) The function 'Fred::operator<' can be const\n", errout.str()); + } }; REGISTER_TEST(TestClass)