[clang] Add Clang attribute to ensure that fields are initialized explicitly (PR #102040)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Sep 27 11:14:02 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}}
----------------
higher-performance wrote:
You have to look at the implementation to see why, but it's because I don't have the name of the field available at that point in the code.
https://github.com/llvm/llvm-project/pull/102040
More information about the cfe-commits
mailing list