Skip to content

Commit ba74606

Browse files
autoantwortclaude
andcommitted
Fix #15080 FP uninitMemberVarNoCtor for const and reference members
A class without constructor whose non-static const or reference member has no default member initializer is not default constructible (or, for a const class type with a default constructor, default constructs it), so the member can never be left uninitialized. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fa6c1f1 commit ba74606

2 files changed

Lines changed: 21 additions & 0 deletions

File tree

‎lib/checkclass.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,10 @@ void CheckClassImpl::constructors()
373373
if (var.typeScope() && var.typeScope()->numConstructors > 0)
374374
continue;
375375

376+
// const and reference members without default initializer must be initialized by every instance
377+
if (var.isConst() || var.isReference())
378+
continue;
379+
376380
if (diagVars.count(&var) == 0)
377381
uninitVarError(var.nameToken(), false, FunctionType::eConstructor, var.scope()->className, var.name(), false, false, true);
378382
}

‎test/testconstructors.cpp‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -797,6 +797,23 @@ class TestConstructors : public TestFixture {
797797
ASSERT_EQUALS("[test.cpp:4:9]: (warning) Member variable 'T::j' has no initializer. [uninitMemberVarNoCtor]\n"
798798
"[test.cpp:8:9]: (warning) Member variable 'U::k' has no initializer. [uninitMemberVarNoCtor]\n",
799799
errout_str());
800+
801+
check("struct S {\n" // const and reference members can't stay uninitialized
802+
" int a = 0;\n"
803+
" const int b;\n"
804+
" int& c;\n"
805+
" const int* d;\n"
806+
"};\n");
807+
ASSERT_EQUALS("[test.cpp:5:16]: (warning) Member variable 'S::d' has no initializer. [uninitMemberVarNoCtor]\n", errout_str());
808+
809+
check("struct S {\n"
810+
" const std::array<std::uint8_t, 2> a;\n"
811+
" const std::vector<std::uint8_t>::const_iterator it;\n"
812+
"};\n"
813+
"S f(const std::vector<std::uint8_t>& v) {\n"
814+
" return S{ {}, v.cbegin() };\n"
815+
"}\n");
816+
ASSERT_EQUALS("", errout_str());
800817
}
801818

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

0 commit comments

Comments
 (0)