如何在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?
我在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++中使用前导下划线,尤其是当与大写字母一起使用时。
相关文章:
- 如何在MISRA C++之后实施CRTP
- 枚举和二进制或运算符(MISRA C++ 2008,4-5-2)
- 如何使用Visual Studio 2008将字符串映射到函数?
- c++:需要正确的语法以避免 MISRA 14-6-1 警告.具有依赖基类的类模板
- 使用 2x1 图块平铺 2xM 数组以最大化差异 - INOI 2008,P2
- MSVC 2008,调试过程,无法调试
- 生成可视C++ 2008 项目时出现链接器错误
- 由于无符号算术运算符的环绕而导致的 MISRA 错误
- Visual Studio 2008 WriteFile
- VS 2008 和 VS 2017 中静态参数的不同行为
- libstdc 是否符合Misra C
- MISRA 警告<复杂表达式隐式转换为不同的基本类型>
- Microsoft Visual Studio 2008,版本9.0.30739.1 SP,DLL构建错误
- Misra C 2008奇怪的警告
- MISRA-C++:2008[8-4-3]:返回函数中的所有出口路径
- MISRA C++ 2008 违反规则 5-2-7:不得直接或间接将指针类型的对象转换为不相关的指针类型
- MISRA C++-2008规则5-0-15-数组索引应是指针算术的唯一形式
- 嵌套交换机案例是否符合MISRA C++2008规则
- 如何在std::map中插入项目而不违反MISRA C++2008必需规则5-2-12
- 交换机外壳标签上的PC棉绒:违反MISRA C++2008要求规则5-0-12