Search code examples
c++misra

How to insert items in std::map without violating MISRA C++ 2008 Required Rule 5-2-12?


I get this error in PC-Lint (au-misra-cpp.lnt):

error 1960: (Note -- Violates MISRA C++ 2008 Required Rule 5-2-12, Array type passed to function expecting a pointer)

On this code:

_IDs["key"] = "value";

The _IDs is declared as:

std::map<std::string,std::string> _IDs;

also tried changing to:

_IDs.insert("key","value");

But get the same error.

How do I get the code to be misra compliant?


Solution

  • The violated rule is calling std::string::string(const CharT* s, const Allocator& alloc = Allocator()), which will decay from char const [] to a char pointer.

    The solution, I think, is to cast explicitely to a pointer type:

    _IDs[static_cast<char const *>("key")] = static_cast<char const *>("value");

    However, I would suggest not using (or at least upgrading) a linter that warns when you actually use std::string.

    Also note that you can't call std::map::insert the way you try to do it. There is no overload which takes the key and the value directly, instead there is an overload which takes a pair consisting of the key and the value. See here overload number 1.