Skip to content

Commit 88b5ddb

Browse files
[clang-tidy]misc-const-correctness fix fake positive when pointer is returned as none const
1 parent e8489c1 commit 88b5ddb

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-pointer-as-pointers.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,33 @@ void ignore_const_alias() {
4848
p_local0 = &a[1];
4949
}
5050

51+
void* ignore_const_return(){
52+
void* const p = nullptr;
53+
return p;
54+
}
55+
56+
void const* const_return(){
57+
void * p = nullptr;
58+
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: pointee of variable 'p' of type 'void *' can be declared 'const'
59+
// CHECK-FIXES: void const* p
60+
return p;
61+
}
62+
63+
template<typename T>
64+
T* ignore_const_return_template(){
65+
T* const p = nullptr;
66+
return p;
67+
}
68+
69+
template<typename T>
70+
T const* const_return_template(){
71+
T * p = nullptr;
72+
// CHECK-MESSAGES: [[@LINE-1]]:3: warning: pointee of variable 'p' of type 'int *' can be declared 'const'
73+
// CHECK-FIXES: T const* p
74+
return p;
75+
}
76+
77+
void instantiate_return_templates() {
78+
ignore_const_return_template<int>();
79+
const_return_template<int>();
80+
}

clang/lib/Analysis/ExprMutationAnalyzer.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -787,10 +787,16 @@ ExprMutationAnalyzer::Analyzer::findPointeeToNonConst(const Expr *Exp) {
787787
// FIXME: false positive if the pointee does not change in lambda
788788
const auto CaptureNoConst = lambdaExpr(hasCaptureInit(Exp));
789789

790+
// Return statement in function with non-const pointer return type
791+
const auto ReturnAsNonConst = returnStmt(
792+
hasDescendant(equalsNode(Exp)),
793+
hasAncestor(functionDecl(returns(NonConstPointerOrDependentType))));
794+
790795
const auto Matches =
791796
match(stmt(anyOf(forEachDescendant(
792797
stmt(anyOf(AssignToNonConst, PassAsNonConstArg,
793-
CastToNonConst, CaptureNoConst))
798+
CastToNonConst, CaptureNoConst,
799+
ReturnAsNonConst))
794800
.bind("stmt")),
795801
forEachDescendant(InitToNonConst))),
796802
Stm, Context);

0 commit comments

Comments
 (0)