[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 Aug 30 02:35:15 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:

This is the only example that I'm torn on because it prohibits writing the very common code:

```
S d;
d.f1 = 123;
d.f3 = 234;
// There's nothing wrong with this multi-line initialization style ^^^
```

While I'm fully on board with the idea that this warning is helpful in cases where aggregate initialization is used, I think I would not restrict the code to use **only** the aggregate initialization.
Especially in C++17 and below, where there is no way to spell the names of the fields in aggregate init syntax.

WDYT about leaving this out? It would also allow us to get rid of the flag we need to store in the class altogether.

Or would this make the warning less useful, to an extent where you don't want to have it?

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


More information about the cfe-commits mailing list