Consider this C++ code:
struct SomeStruct {
SomeStruct() noexcept;
};
//SomeStruct::SomeStruct() noexcept {}
class SomeClass {
const bool b;
const SomeStruct s;
public:
SomeClass() : b(true) {}
operator bool() const { return b; }
};
void f() {
int *p = new int;
if (SomeClass())
delete p;
}
When I run clang --analyze -Xanalyzer -analyzer-output=text
on it, I get this:
q72007867.cpp:20:1: warning: Potential leak of memory pointed to by 'p' [cplusplus.NewDeleteLeaks]
}
^
q72007867.cpp:17:12: note: Memory is allocated
int *p = new int;
^~~~~~~
q72007867.cpp:18:7: note: Assuming the condition is false
if (SomeClass())
^~~~~~~~~~~
q72007867.cpp:18:3: note: Taking false branch
if (SomeClass())
^
q72007867.cpp:20:1: note: Potential leak of memory pointed to by 'p'
}
^
1 warning generated.
Uncommenting the definition of SomeStruct
's constructor makes the warning go away, though. Swapping the order of const bool b;
and const SomeStruct s;
also makes it go away. In the original program, is there actually some other definition of SomeStruct
's constructor that would lead to the false branch being taken there, or is this a false positive in Clang's static analyzer?