C++静态分析,模板类

C++ static analysis, template classes

本文关键字:静态分析 C++      更新时间:2023-10-16

我需要一个静态分析器来查找未初始化的变量成员/变量...的模板化类类型。

任何分析仪都能做到这一点吗?我尝试了clang/cppcheck和其他几个没有运气。

这是我的测试代码:

enum class ViewMode
{
One   = 1,
Two     = 2,
Three  = 3,
Four     = 4
};
class TestClass {
public:
TestClass() {}
};
template<typename T, bool C = std::is_copy_constructible<T>::value>
class TemplateTest
{
public:
TemplateTest() {}
TemplateTest(const T& value)
: value_(value)
{}
TemplateTest(const TemplateTest&) = delete;
TemplateTest(TemplateTest<T, C>&& rhs)
: value_(std::move(rhs.value_))
{}
TemplateTest(T&& value)
: value_(std::move(value))
{}
private:
T value_;
};
class StaticAnalysisTest {
public:
StaticAnalysisTest() {}
void DoSomething() {
}
private:
ViewMode viewMode_;     //this uninitialized warning is found
TemplateTest<ViewMode> viewMode2_; //this one is not
};

我进一步将问题提炼为:

class Foo
{
private:
int m_nValue;
public:
Foo() {};
Foo(int value) : m_nValue(value) {}
int GetValue() { return m_nValue; }
};
class Bar
{
public:
Bar(){}
void DoSomething() {
Foo foo;
}
};

这不会生成单位化变量警告,但是当我注释掉时:

//Foo(int value) : m_nValue(value) {}

它确实如此

感谢您评估 Cppcheck。对于第二个示例,如果您添加 --inconclusive 标志,则会发出警告,例如:

class Foo
{
private:
int m_nValue;
public:
Foo() {};
explicit Foo(int value) : m_nValue(value) {}
int GetValue() const
{
return m_nValue;
}
};
class Bar
{
public:
Bar() {}
static void DoSomething() {
Foo foo;
}
};

Cppcheck 的输出

$ cppcheck --enable=all --inconclusive uninitmembervar.cpp 
[uninitmembervar.cpp:6]: (warning, inconclusive) Member variable 'Foo::m_nValue' is not initialized in the constructor.