From e09b0330e4557a640cd7e506286ceb9e728198ac Mon Sep 17 00:00:00 2001 From: Kamil Dudka Date: Sun, 8 Jan 2012 12:17:55 +0100 Subject: [PATCH] Class: Don't warn about uninitialized union members because they are often combined with a second variable --- lib/checkclass.cpp | 7 +++++-- test/testclass.cpp | 22 ++++++++++++++++++++-- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 2383b0f4a..e9425edd1 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -142,8 +142,11 @@ void CheckClass::constructors() if (classNameUsed) operatorEqVarError(func->token, scope->className, var->name()); - } else if (func->access != Private) - uninitVarError(func->token, scope->className, var->name()); + } else if (func->access != Private) { + const Scope *varType = var->type(); + if (!varType || varType->type != Scope::eUnion) + uninitVarError(func->token, scope->className, var->name()); + } } } } diff --git a/test/testclass.cpp b/test/testclass.cpp index a7fde6e92..1b27fc82a 100644 --- a/test/testclass.cpp +++ b/test/testclass.cpp @@ -81,7 +81,8 @@ private: TEST_CASE(uninitVarArray3D); TEST_CASE(uninitVarStruct1); // ticket #2172 TEST_CASE(uninitVarStruct2); // ticket #838 - TEST_CASE(uninitVarUnion); // ticket #3196 + TEST_CASE(uninitVarUnion1); // ticket #3196 + TEST_CASE(uninitVarUnion2); TEST_CASE(uninitMissingFuncDef); // can't expand function in constructor TEST_CASE(privateCtor1); // If constructor is private.. TEST_CASE(privateCtor2); // If constructor is private.. @@ -2560,7 +2561,7 @@ private: ASSERT_EQUALS("", errout.str()); } - void uninitVarUnion() { // ticket #3196 + void uninitVarUnion1() { // ticket #3196 checkUninitVar("class Fred\n" "{\n" "private:\n" @@ -2572,6 +2573,23 @@ private: ASSERT_EQUALS("", errout.str()); } + void uninitVarUnion2() { + // If the "data_type" is 0 it means union member "data" is invalid. + // So it's ok to not initialize "data". + // related forum: http://sourceforge.net/apps/phpbb/cppcheck/viewtopic.php?f=3&p=1806 + checkUninitVar("union Data { int id; int *ptr; };\n" + "\n" + "class Fred {\n" + "private:\n" + " int data_type;\n" + " Data data;\n" + "public:\n" + " Fred() : data_type(0)\n" + " { }\n" + "};\n"); + ASSERT_EQUALS("", errout.str()); + } + void uninitMissingFuncDef() { // Unknown member function checkUninitVar("class Fred\n"