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

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Fri Sep 13 05:15:33 PDT 2024


================
@@ -1472,3 +1472,49 @@ template<typename T> struct Outer {
   };
 };
 Outer<int>::Inner outerinner;
+
+void aggregate() {
+  struct S {
+    [[clang::requires_explicit_initialization]] int x;
+    int y;
+    int z = 12;
+    [[clang::requires_explicit_initialization]] int q = 100;
+    static void foo(S) { }
+  };
+
+  struct D : S { // expected-warning {{not explicitly initialized}}
+    int f1;
+    int f2 [[clang::requires_explicit_initialization]];
+  };
+
+  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 {{'q' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}}
+  S s{.x = 100, .q = 100};
+  (void)s;
+  S t{.q = 100}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'x' is not explicitly initialized}}
+  (void)t;
+  S *ptr1 = new S; // expected-warning {{not explicitly initialized}}
+  delete ptr1;
+  S *ptr2 = new S{.x = 100, .q = 100};
+  delete ptr2;
+#if __cplusplus >= 202002L
+  D a({}, 0); // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'f2' is not explicitly initialized}}
+  (void)a;
+#else
+  C a; // expected-warning {{not explicitly initialized}}
+  (void)a;
+#endif
+  D b{.f2 = 1}; // expected-warning {{'x' is not explicitly initialized}} expected-warning {{'q' is not explicitly initialized}}
----------------
ilya-biryukov wrote:

As an idea for future improvements: we could also collect all unitialized fields and emit a single diagnostic that lists them all (with notes to the locations of the fields).

However, I think this is good enough for the first version, I don't necessarily feel we should do it right away.

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


More information about the cfe-commits mailing list