Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -351,16 +351,20 @@ void CheckClass::constructors()

// Variables with default initializers
bool hasAnyDefaultInit = false;
bool hasAnySelfInit = false;
const bool cpp14OrLater = mSettings->standards.cpp >= Standards::CPP14;
for (Usage& usage : usageList) {
const Variable& var = *usage.var;

// check for C++11 initializer
if (var.hasDefault()) {
usage.init = true;
hasAnyDefaultInit = true;
} else if (cpp14OrLater && !hasAnySelfInit && isInitialized(usage, FunctionType::eConstructor)) {
hasAnySelfInit = true;
}
}
if (!hasAnyDefaultInit)
if (!hasAnyDefaultInit && !hasAnySelfInit)
continue;

handleUnionMembers(usageList);
Expand All @@ -371,6 +375,9 @@ void CheckClass::constructors()
continue;

const Variable& var = *usage.var;
if (var.typeScope() && var.typeScope()->numConstructors > 0)
continue;

if (diagVars.count(&var) == 0)
uninitVarError(var.nameToken(), false, FunctionType::eConstructor, var.scope()->className, var.name(), false, false, true);
}
Expand Down
28 changes: 28 additions & 0 deletions test/testconstructors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,34 @@ class TestConstructors : public TestFixture {
" int a, b;\n"
"};\n");
ASSERT_EQUALS("", errout_str());

check("struct S {\n"
" explicit S(int);\n"
" S(const S&);\n"
" int i;\n"
"};\n"
"struct T {\n"
" S s;\n"
" int j{};\n"
"};\n");
ASSERT_EQUALS("", errout_str());

const char code[] = "struct S { int i = 0; };\n" // #14697
"struct T {\n"
" S s;\n"
" int j;\n"
"};\n"
"struct U {\n"
" std::string a;\n"
" int k;\n"
"};\n";
const Settings s = settingsBuilder(settings).cpp(Standards::CPP11).build();
check(code, s);
ASSERT_EQUALS("", errout_str());
check(code);
ASSERT_EQUALS("[test.cpp:4:9]: (warning) Member variable 'T::j' has no initializer. [uninitMemberVarNoCtor]\n"
"[test.cpp:8:9]: (warning) Member variable 'U::k' has no initializer. [uninitMemberVarNoCtor]\n",
errout_str());
}

// ticket #4290 "False Positive: style (noConstructor): The class 'foo' does not have a constructor."
Expand Down
Loading