Search code examples
c++klocwork

Klockwork scan c++ Template value


 > -Severity (Error)
 > -ID(local): 1
 > -Code: UNINIT.CTOR.MUST --> IPCAtomic()
 > -Message: 'this->value' is not initialized in this constructor.
 > -Details:
 > 
 > 'this->value' is not initialized in this constructor.
 > 
 > * CommunicationTypes.h:198: 'this->value' is used, but is
 > uninitialized.
 > 
 > * CommunicationTypes.h:198: List of instantiations (may be
 > incomplete)
 > 
 > * CommunicationTypes.h:198: <anonymous>::IPCAtomic< ,
 > >::#constructor
 > 
 > Current status 'Analyze'

This is the code I have, I also tried other options, but KW still produces the same error

     template <typename T, typename SerializeAs = T>
class IPCAtomic : public IPCBundleIfc
{
    typedef IPCAtomic<T, SerializeAs> MyType;
public:
    T value;

    IPCAtomic() : value(T())
    {
    }

    IPCAtomic(T v) : value(v)
    {
        static_assert(!std::is_base_of<IPCBundleIfc, T>::value, "type parameter of this class can not derive from IPCBundleIfc");
    }

    virtual ~IPCAtomic() {}

    operator T& ()
    {
        return value;
    }

    MyType& operator=(const T& v)
    {
        if (&v != &value)
        {
            value = v;
        }

        return *this;
    }

    bool operator==(const T& v) const
    {
        return value == v;
    }

    bool operator==(const MyType& v) const
    {
        return value == v.value;
    }

Can you offer any solutions?


Solution

  • To initialize templated member values, use list initialization instead of initializing from a default constructed object.

    Like this :

    IPCAtomic() : 
        value{}
    {
    }
    
    // when initializing with a value use const T& this avoids 
    // unecessary copies. Also make constructors with one parameter
    // explicit so they can't accidentaly be used as type conversions.
    explicit IPCAtomic(const T& v) : 
        value{v}
    {
    }
    
    // allow efficient initialization from temporaries
    explicit IPCAtomic(T&& v) : 
       value{v}
    {
    }