Martijn - 2022-09-29

Consider the following 2 source files, defining a template class called test.

File main.cpp

namespace
{
    template<typename T>
    class test
    {
        T m_i;
    public:
        newtest() : m_i(0) {}
    };
}
test<int> n;

File other.cpp

namespace
{
    template<typename T>
    class test
    {
        T m_i;
        T m_j;
    public:
        newtest() : m_i(0), m_j(0) {}
    };
}
test<int> n;

In this case, double definition issues should be prevented by using anonymous namespaces. However, when running this code through cppcheck (version 2.9) I get a ctuOneDefinitionRuleViolation. When changing the anonymous namespaces to named namespaces, the warning goes away, When using non-template classes this principle seems to work correctly, but when using templates, something seems to fail.

When looking at the cppcheck debug output, cppcheck sewems to incorrectly create a template instance definition outside of the anonymous namespace. This goes well with named namespaces, but goes wrong for anonymous namespaces. It should probably define the instantiation of the class using class ::newtest<int></int>

Checking src\main.cpp ...

##file src/main.cpp
1: namespace
2: {
3: class newtest<int> ;
4:
|
10:
11: }
12: newtest<int> n@var1 ;
4: class newtest<int>
5: {
6: int m_i@var2 ;
7: public:
8: newtest<int> ( ) : m_i@var2 ( 0 )
9: { }
10: } ;

##Value flow
Line 8
  0 always 0
 

Last edit: Martijn 2022-09-29