[clang] Add Clang attribute to ensure that fields are initialized explicitly (PR #102040)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 27 11:06:34 PDT 2024


================
@@ -1472,3 +1472,56 @@ template<typename T> struct Outer {
   };
 };
 Outer<int>::Inner outerinner;
+
+void aggregate() {
+  struct NonAgg {
+    NonAgg() { }
+    [[clang::requires_explicit_initialization]] int f;  // expected-warning {{attribute is ignored}}
+  };
+  NonAgg nonagg;
+  (void)nonagg;
+
+  struct S {
+    [[clang::requires_explicit_initialization]] int x; // expected-note 4{{declared here}}
+    int y;
+    int z = 12;
+    [[clang::requires_explicit_initialization]] int q = 100; // expected-note 4{{declared}}
+    static void foo(S) { }
+  };
+
+  struct D : S { // expected-warning {{field in 'S' is not explicitly initialized, but was marked as requiring explicit initialization}}
+    int f1;
+    int f2 [[clang::requires_explicit_initialization]]; // expected-note 2{{declared}}
+  };
+
+  struct C {
+    [[clang::requires_explicit_initialization]] int w;
+    C() = default;  // Test pre-C++20 aggregates
+  };
+
+  S::foo(S{1, 2, 3, 4});
+  S::foo(S{.x = 100, .q = 100});
+  S::foo(S{.x = 100}); // expected-warning {{field 'q' is not explicitly initialized, but was marked as requiring explicit initialization}}
+  S s{.x = 100, .q = 100};
+  (void)s;
+  S t{.q = 100}; // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}}
+  (void)t;
+  S *ptr1 = new S; // expected-warning {{field in 'S' is not explicitly initialized, but was marked as requiring explicit initialization}}
+  delete ptr1;
+  S *ptr2 = new S{.x = 100, .q = 100};
+  delete ptr2;
+#if __cplusplus >= 202002L
+  D a({}, 0); // expected-warning {{field 'x' is not explicitly initialized, but was marked as requiring explicit initialization}} expected-warning {{field 'f2' is not explicitly initialized, but was marked as requiring explicit initialization}}
+  (void)a;
+#else
+  C a; // expected-warning {{field in 'C' is not explicitly initialized, but was marked as requiring explicit initialization}}
----------------
erichkeane wrote:

Why do we have the 'in' on the diagnostic here?  It seems we should know the field, right?  Or did I forget something from earlier?

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


More information about the cfe-commits mailing list