[clang-tools-extra] [clang-tidy] The first PR our of many PRs for the "Initialized Class Members" check. (PR #65189)

Gábor Horváth via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 8 12:03:50 PDT 2023


================
@@ -0,0 +1,107 @@
+//===--- CppInitClassMembersCheck.cpp - clang-tidy ------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include <string>
+
+#include "CppInitClassMembersCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::google {
+
+namespace {
+
+// Matches records that have a default constructor.
+AST_MATCHER(CXXRecordDecl, hasDefaultConstructor) {
+  return Node.hasDefaultConstructor();
+}
+
+// Returns the names of `Fields` in a comma separated string.
+std::string
+toCommaSeparatedString(const ArrayRef<const FieldDecl *> &Fields) {
+  std::string Buffer;
+  llvm::raw_string_ostream OS(Buffer);
+  llvm::interleave(
+      Fields, OS, [&OS](const FieldDecl *Decl) { OS << Decl->getName(); },
+      ", ");
+  return Buffer;
+}
+
+// Returns `true` for types that have uninitialized values by default. For
+// example, returns `true` for `int` because an uninitialized `int` field or
+// local variable can contain uninitialized values.
+bool isDefaultValueUninitialized(QualType Ty) {
+  if (Ty.isNull())
+    return false;
+
+  // FIXME: For now, this check focuses on several allowlisted types. We will
----------------
Xazax-hun wrote:

I wonder if you will need to do more than checking for a couple fo types.

For example, consider the scenario:
```
// 3rdPartyHeader.h:
struct OthersPair { int first, second; };

// MyCode:
struct MyStruct {
 int a = 1;
 OthersPair p;
};
```

Here, the user might have no control over OthersPair, it is coming from a 3rd party library. It does not have a constructor to initialize its members, so we need to add member initializers in `MyStruct`.

https://github.com/llvm/llvm-project/pull/65189


More information about the cfe-commits mailing list