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
4 changes: 4 additions & 0 deletions lib/checkclass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,10 @@ void CheckClassImpl::constructors()
if (var.typeScope() && var.typeScope()->numConstructors > 0)
continue;

// const and reference members without default initializer must be initialized by every instance

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This check should be done in the loop above (see hasAnyDefaultInit etc.). A const/ref member should inhibit warnings for any other members as well.

if (var.isConst() || var.isReference())
continue;

if (diagVars.count(&var) == 0)
uninitVarError(var.nameToken(), false, FunctionType::eConstructor, var.scope()->className, var.name(), false, false, true);
}
Expand Down
17 changes: 17 additions & 0 deletions test/testconstructors.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,23 @@ class TestConstructors : public TestFixture {
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());

check("struct S {\n" // const and reference members can't stay uninitialized
" int a = 0;\n"
" const int b;\n"
" int& c;\n"
" const int* d;\n"
"};\n");
ASSERT_EQUALS("[test.cpp:5:16]: (warning) Member variable 'S::d' has no initializer. [uninitMemberVarNoCtor]\n", errout_str());

check("struct S {\n"
" const std::array<std::uint8_t, 2> a;\n"
" const std::vector<std::uint8_t>::const_iterator it;\n"
"};\n"
"S f(const std::vector<std::uint8_t>& v) {\n"
" return S{ {}, v.cbegin() };\n"
"}\n");
ASSERT_EQUALS("", errout_str());
}

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