From 8ce0faf7231eee7595edf10a3d3d12e434691870 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Mon, 2 May 2022 16:49:13 +0200 Subject: [PATCH] Fix #10427 Regression: selfInitialization (#4070) --- lib/checkclass.cpp | 12 ++++++++++-- test/testclass.cpp | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index f3e4e7fd0..374cee66b 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -2504,8 +2504,16 @@ void CheckClass::checkSelfInitialization() continue; for (; tok != scope->bodyStart; tok = tok->next()) { - if (Token::Match(tok, "[:,] %var% (|{ %var% )|}") && tok->next()->varId() == tok->tokAt(3)->varId()) { - selfInitializationError(tok, tok->strAt(1)); + if (Token::Match(tok, "[:,] %var% (|{")) { + const Token* varTok = tok->next(); + if (Token::Match(varTok->astParent(), "(|{")) { + if (const Token* initTok = varTok->astParent()->astOperand2()) { + if (initTok->varId() == varTok->varId()) + selfInitializationError(tok, varTok->str()); + else if (initTok->isCast() && ((initTok->astOperand1() && initTok->astOperand1()->varId() == varTok->varId()) || (initTok->astOperand2() && initTok->astOperand2()->varId() == varTok->varId()))) + selfInitializationError(tok, varTok->str()); + } + } } } } diff --git a/test/testclass.cpp b/test/testclass.cpp index 018dfaee1..830dedb30 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -7186,6 +7186,22 @@ private: "}"); ASSERT_EQUALS("[test.cpp:5]: (error) Member variable 'i' is initialized by itself.\n", errout.str()); + checkSelfInitialization("class A {\n" // #10427 + "public:\n" + " explicit A(int x) : _x(static_cast(_x)) {}\n" + "private:\n" + " int _x;\n" + "};\n"); + ASSERT_EQUALS("[test.cpp:3]: (error) Member variable '_x' is initialized by itself.\n", errout.str()); + + checkSelfInitialization("class A {\n" + "public:\n" + " explicit A(int x) : _x((int)(_x)) {}\n" + "private:\n" + " int _x;\n" + "};\n"); + ASSERT_EQUALS("[test.cpp:3]: (error) Member variable '_x' is initialized by itself.\n", errout.str()); + checkSelfInitialization("class Fred {\n" " std::string s;\n" " Fred() : s(s) {\n"