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

StackOverflow https://stackoverflow.com/questions/16852996

  •  30-05-2022
  •  | 
  •  

문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

// a template function that takes an array of char 
//  and returns a std::string constructed from it
//
// This function safely 'converts' the array to a pointer
//  to it's first element, just like the compiler would
//  normally do, but this should avoid diagnostic messages
//  from very restrictive lint settings that don't approve
//  of passing arrays to functions that expect pointers.
template <typename T, size_t N>
std::string str( T (&arr)[N])
{
    return std::string(&arr[0]);
}

Using the above template function, you should be able to get past the linter like so:

_IDs[str("key")] = str("value");

As an aside - I'm surprised lint isn't complaining that _IDs is a reserved name - you should avoid leading underscores in C or C++, especially when used along with caps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top