主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C++:2008 Rule 7-3-4

using-directives shall not be used

描述

规则定义

using-directives shall not be used. 1

理由

using 指令可能会无意中将超过您预期的变量暴露给名称查找。名称查找范围的扩大增加了变量被意外使用的可能性。例如:

namespace NS {
    int i;
    int j;
}
using namespace NS;
该代码同时暴露了 NS::iNS::j 变量供名称查找,但您可能仅打算使用其中一个变量。

建议仅暴露您打算使用的变量,或在使用变量时通过其全限定名称进行引用。例如,在前面的示例中,如果您使用变量 NS::i,则只将此变量暴露给名称查找:

using NS::i;
或在所有情况下使用 NS::i 代替 i

Polyspace 实现

规则检查器报告了 using 指令的违规情况。这些指令包含关键字 using,后跟关键字 namespace 和命名空间的名称。using 指令使命名空间中的所有成员在当前范围内可用。

检查项不会对 using 声明进行标记。这些声明还包含关键字 using,但不包含关键字 namespaceusing 声明只暴露命名空间中的特定成员。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

namespace currentDataModel {
    int nodes;
    int count;
}
using namespace currentDataModel; //Noncompliant

namespace lastDataModel {
    int nodes;
    int count;
}
using lastDataModel::count; //Compliant

在此示例中,暴露命名空间 currentDataModel 的所有成员的 using 指令违反了该规则。

检查信息

组:声明
类别:必需

版本历史记录

在 R2013b 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.