【问题标题】:How to insert items in std::map without violating MISRA C++ 2008 Required Rule 5-2-12?如何在不违反 MISRA C++ 2008 所需规则 5-2-12 的情况下在 std::map 中插入项目?
【发布时间】:2013-05-31 08:28:06
【问题描述】:

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

错误 1960:(注意——违反 MISRA C++ 2008 要求的规则 5-2-12, 数组类型传递给期望指针的函数)

关于此代码:

_IDs["key"] = "value";

_ID 声明为:

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

也试过改成:

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

但得到同样的错误。

如何让代码符合 misra 标准?

【问题讨论】:

  • MISRA 对不使用reserved names 有什么要说的吗?如果不是,C++ 标准当然可以。
  • 是的,它不喜欢下划线。违反 MISRA C++ 2008 规定的规则 17-0-2,C++ 标识符模式的重用。

标签: c++ misra


【解决方案1】:

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

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

_IDs[static_cast&lt;char const *&gt;("key")] = static_cast&lt;char const *&gt;("value");

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

另请注意,您不能以您尝试这样做的方式致电std::map::insert。没有直接采用键和值的重载,而是采用由键和值组成的对的重载。请参阅here 过载编号 1。

【讨论】:

  • 很明显,遵循 MISRA 如何生成更易于阅读和易于维护的代码:-P
  • @Angew:MISRA 的目的是让代码更难阅读和维护。这样,维护者就不太可能认为他们理解代码,并根据不完整的知识进行重大更改。通过将代码转换为乱码,MISRA 在进行最小的更改之前强制进行完整的分析。因此,代码更稳定。
  • @MikeSeymour 有趣的方法。但是,我想说这也使代码更难首先审查/验证。不过,我(有点)明白你提出的观点。
  • 静态转换处理违反 5-2-12。
  • @Angew:同样,通过使这些事情变得更难,MISRA 造成的混淆迫使审阅者对代码进行极其详细的分析。没有试图掩盖“明显”正确的部分,因为没有什么是显而易见的。对于大多数软件开发来说,这将是疯狂的。但是对于安全关键代码,您需要将每一行都视为潜在的恶意代码,并且使每一行不可读是实现这一目标的一种方法。
【解决方案2】:
// 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]);
}

使用上面的模板函数,你应该可以像这样通过 linter:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 2018-06-16
    相关资源
    最近更新 更多