主要内容

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

AUTOSAR C++14 Rule A8-5-2

Braced-initialization {}, without equals sign, shall be used for variable initialization

描述

规则定义

Braced-initialization {}, without equals sign, shall be used for variable initialization.

理由

花括号初始化:

classType Object{arg1, arg2, ...};
比其他形式的初始化更明确。带括号初始化具有以下优点:

  • 防止隐式类型转换,例如从 double 转换为 float

  • 避免了导致最令人头疼的语法分析问题的模糊语法。

    例如,声明中指出:

    ResourceType aResource();
    目前尚不清楚 aResource 是一个返回类型为 ResourceType 的变量函数,还是类型为 ResourceType 的对象。

    有关详细信息,请参阅声明语法具有多义性

该规则还禁止使用 = 符号进行初始化,因为 = 符号可能会让人误以为在不需要赋值或复制构造函数的情况下,赋值或复制构造函数被调用。

Polyspace 实现

通常,检查项使用以下格式标记数据类型为 Type 的对象 obj1 的初始化:

  • Type obj1 = obj2;
  • Type obj1(obj2);

检查项允许以下情况出现例外:

  • 使用简单的赋值给常量、变量、lambda 表达式、标准初始化列表或函数调用来初始化类型为 auto 的变量。

  • 使用简单赋值初始化引用类型

  • 使用格式 Type a() 的全球范围声明,其中 Type 是具有默认构造函数的类类型。分析将 a 解释为返回类型 Type 的函数。

  • OpenMP 并行循环中的循环变量初始化在 for 循环中,即在紧跟 #pragma omp parallel forfor 循环语句中。

只有指定 C++ 版本为 C++11 或更高版本时,检查项才启用。请参阅 C++ 标准版本 (-cpp-version)

故障排除

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

示例

全部展开

class ResourceType {
      int memberOne;
      int memberTwo;
    public:
      ResourceType() {memberOne = 0; memberTwo = 0;}
      ResourceType(int m, int n) {memberOne = m; memberTwo = n;}
      ResourceType(ResourceType &anotherResource) {
          memberOne = anotherResource.memberTwo;
          memberTwo = anotherResource.memberOne;
      }
};

void func() {
    ResourceType aResourceOne(); //Noncompliant
    ResourceType aResourceTwo(1, 2); //Noncompliant
    ResourceType aResourceThree = {1,2};   //Noncompliant
     
    ResourceType aResourceFour{1,2}; //Compliant

}

在此示例中,函数 func 声明了四个类型为 ResourceType 的对象。只有 aResourceFour 的声明没有违反这条规则。

aResourceOneaResourceTwoaResourceThree 的声明违反了规则。尤其是:

  • aResourceOne 的声明存在最令人困惑的解析问题。尚不清楚 aResourceOne 是类型为 ResourceType 的对象,还是返回类型为 ResourceType 的对象的函数。

  • aResourceThree 的声明似乎表明,初始化时调用了复制构造函数 ResourceType(ResourceType &)。复制构造函数将数据成员 memberOne 初始化为 2,并将 memberTwo 初始化为 1。然而,构造函数 ResourceType(int, int) 被调用。此构造函数将数据成员 memberOne 初始化为 1,并将 memberTwo 初始化为 2。

检查信息

组:声明符
类别:必需、自动

版本历史记录

在 R2019a 中推出