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

via cfe-commits cfe-commits at lists.llvm.org
Fri Aug 30 10:26:29 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}}
----------------
higher-performance wrote:

I don't think we should leave this out. Allowing this big of a loophole would defeat the purpose of the attribute, which is to ensure that callers don't forget to initialize a field that has been added to the struct.

The best analogy I would think of here is function parameters. If a parameter is added, an argument must be passed for it -- we don't attempt to provide callers a way to work around that; that's a hard requirement, and by design.

Note that if the diagnostic caused retroactive errors in _existing_ code, I would agree. But all it does is to merely trigger a warning for the applicable fields moving forward. It's up to the author of the field to determine if this is what they want -- if it isn't, then they can just avoid applying it.

I _could_ see a future where Clang slightly relaxes the requirement to allow that coding style, iff it can prove that the fields are all trivial & then assigned to prior the usage of the object. That seems perfectly fine to me, because at no point it opens such a loophole. (Also note that closing a loophole we left open will be much more painful than relaxing the syntactic requirement.)

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


More information about the cfe-commits mailing list