File tree Expand file tree Collapse file tree
Best Practices/Unused Entities
test/query-tests/Best Practices/Unused Entities Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -46,6 +46,8 @@ predicate declarationHasSideEffects(Variable v) {
4646 )
4747 or
4848 v .getType ( ) instanceof TemplateDependentType // may have a constructor/destructor
49+ or
50+ v .getInitializer ( ) .getExpr ( ) .mayBeImpure ( )
4951}
5052
5153from LocalVariable v , Function f
Original file line number Diff line number Diff line change @@ -15,6 +15,8 @@ import cpp
1515
1616predicate declarationHasSideEffects ( Variable v ) {
1717 exists ( Class c | c = v .getUnspecifiedType ( ) | c .hasConstructor ( ) or c .hasDestructor ( ) )
18+ or
19+ v .getInitializer ( ) .getExpr ( ) .mayBeImpure ( )
1820}
1921
2022from Variable v
Original file line number Diff line number Diff line change 1+ ---
2+ category : minorAnalysis
3+ ---
4+ * The ` cpp/unused-local-variable ` and ` cpp/unused-static-variable ` queries no longer report variables whose initializers may have side effects.
Original file line number Diff line number Diff line change 44| code2.cpp:26:16:26:17 | v1 | Variable v1 is not used. |
55| code2.cpp:42:11:42:16 | myVar1 | Variable myVar1 is not used. |
66| code2.cpp:64:7:64:8 | v3 | Variable v3 is not used. |
7- | code2.cpp:108:11:108:12 | v2 | Variable v2 is not used. |
87| code2.cpp:128:9:128:9 | b | Variable b is not used. |
98| code.c:10:18:10:18 | y | Variable y is not used. |
109| code.c:11:18:11:18 | z | Variable z is not used. |
Original file line number Diff line number Diff line change @@ -105,7 +105,7 @@ void test_range_based_for()
105105 output (v1);
106106 }
107107
108- for (int v2 : myContainer) // $ Alert // BAD: v2 is not used
108+ for (int v2 : myContainer) // GOOD: iterator dereference may have side effects
109109 {
110110 }
111111}
@@ -181,3 +181,15 @@ void test_maybe_unused()
181181{
182182 [[maybe_unused]] int unused; // GOOD: explicitly marked as maybe_unused
183183}
184+
185+ int globalVar;
186+
187+ int initialize ()
188+ {
189+ return ++globalVar;
190+ }
191+
192+ void test_initializer_side_effect ()
193+ {
194+ int initialized = initialize (); // GOOD (initializer has a side effect)
195+ }
Original file line number Diff line number Diff line change @@ -29,3 +29,23 @@ class MyTemplateClass // never instantiated
2929 // ...
3030 }
3131};
32+
33+ int initialize ()
34+ {
35+ return ++globalVar;
36+ }
37+
38+ static int initialized = initialize(); // GOOD (initializer has a side effect)
39+
40+ struct WithConstructor
41+ {
42+ WithConstructor () { ++globalVar; }
43+ };
44+
45+ struct WithDestructor
46+ {
47+ ~WithDestructor () { ++globalVar; }
48+ };
49+
50+ static WithConstructor constructed; // GOOD (constructor has a side effect)
51+ static WithDestructor destructed; // GOOD (destructor has a side effect)
You can’t perform that action at this time.
0 commit comments