如何在std::map中插入项目而不违反MISRA C++2008必需规则5-2-12

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

本文关键字:C++2008 MISRA 规则 5-2-12 std map 插入项目      更新时间:2023-10-16

我在PC Lint(au misra cpp.lnt(:中收到此错误

error 1960:(注--违反了MISRA C++2008要求的规则5-2-12,传递给需要指针的函数的数组类型(

在此代码上:

_IDs["key"] = "value";

ID声明为:

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

还尝试更改为:

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

但是得到了同样的错误。

如何使代码符合misra?

违反的规则正在调用std::string::string(const CharT* s, const Allocator& alloc = Allocator()),它将从char const []衰减为char指针。

我认为,解决方案是显式地转换为指针类型:

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

然而,我建议不要使用(或者至少升级(当您实际使用std::string时会发出警告的linter。

还要注意,你不能用你尝试的方式调用std::map::insert。没有直接接受键和值的重载,而是有一个接受由键和值组成的对的重载。请参阅此处的过载编号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]);
}

使用上面的模板功能,你应该能够像这样通过过梁:

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

顺便说一句——我很惊讶lint没有抱怨_IDs是一个保留名称——你应该避免在C或C++中使用前导下划线,尤其是当与大写字母一起使用时。