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

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Wed Sep 4 02:51:55 PDT 2024


================
@@ -1472,3 +1472,25 @@ template<typename T> struct Outer {
   };
 };
 Outer<int>::Inner outerinner;
+
+void aggregate() {
+  struct B {
+    [[clang::explicit_init]] int f1;
+  };
+
+  struct S : B { // expected-warning {{uninitialized}}
+    int f2;
+    int f3 [[clang::explicit_init]];
+  };
+
+#if __cplusplus >= 202002L
+  S a({}, 0);  // expected-warning {{'f1' is left uninitialized}} expected-warning {{'f3' is left uninitialized}}
+#endif
+  S b{.f3 = 1}; // expected-warning {{'f1' is left uninitialized}}
+  S c{.f2 = 5}; // expected-warning {{'f1' is left uninitialized}} expected-warning {{'f3' is left uninitialized}} expected-warning {{'f3' is left uninitialized}}
+  c = {{}, 0};  // expected-warning {{'f1' is left uninitialized}} expected-warning {{'f3' is left uninitialized}}
+  S d; // expected-warning {{uninitialized}} expected-note {{constructor}}
----------------
ilya-biryukov wrote:

Okay, fair point, and I agree. 

I still feel that using this consistently in C++17 would be a challenge, but people are also free to disable this warning in C++17 **or** if they like multi-line initialization in C++20.

To give the discussions a more useful spin: I suspect we could remove some of these warnings if we are willing to pay for a more advanced analysis in Clang. It's technically possible to check that those fields of a struct are initialized before being read in certain scenarios. The most obvious one is when all initializations are inside a single function. Currently, we would warn when the struct is created, but with the more advanced analysis we may remove this restriction in "obviously safe" cases, which is a strict improvement.

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


More information about the cfe-commits mailing list