【发布时间】:2017-02-22 10:10:23
【问题描述】:
规则 7-1-1(必需)未修改的变量应为 const 限定
如果一个变量不需要修改,那么它应该是 使用 const 限定条件声明,使其不能被修改。一种 非参数变量将需要在 声明点。此外,未来的维护不能意外 修改值。
void b ( int32_t * ); int32_t f ( int32_t * p1, // Non-compliant int32_t * const p2, // Compliant int32_t * const p3 ) // Compliant { *p1 = 10; *p2 = 10; b( p3 ); int32_t i = 0; // Non-compliant return i; }
标准中包含的示例侧重于指针。该规则要求所有满足条件的指针都是const,例如int * const。如果我理解正确,它不需要需要指针和引用来指向const 对象,例如const int * 或 const int &。事实上,它被另一条规则所涵盖(但仅限于参数!):
Rule 7-1-2 (Required) 如果对应的对象没有被修改,函数中的指针或引用参数应声明为指向 const 的指针或对 const 的引用
那么,规则 7-1-1 是否适用于引用?引用在创建后无法重新绑定,因此应将其视为const 指针。因此,所有引用都应自动遵守规则 7-1-1。
编辑(基于 Lightness Races in Orbit、Richard Critten 和 Peter 的 cmets 以及我的实验): 或者该规则是否适用于引用对象的类型在参考的情况下?我的意思是const int & 与int & 类似于const int 与int?
我之所以问,是因为我的 MISRA C++ 检查器不断报告引用的违规行为……其行为示例:
class A
{
int property;
public:
A(int param) : property(param) {} // violation: should be: const int param
int get_property() const { return property; }
void set_property(int param) { property = param; } // violation: should be: const int param
};
class ConstA
{
const int property;
public:
ConstA(int param) : property(param) {} // violation: should be: const int param
int get_property() const { return property; }
// setter not allowed
};
void example1()
{
const A const_obj_A(1);
A nonconst_obj_A(2);
ConstA nonconst_obj_constA(3); // OK: used to create a non-const reference
const A& const_ref_A = nonconst_obj_A;
A& nonconst_ref_A = nonconst_obj_A; // OK: setter called
nonconst_ref_A.set_property(4);
ConstA& const_ref_constA = nonconst_obj_constA; // violation: no modification
// In fact, it seems to be impossible to make
// a non-violating ConstA& declaration.
// The only chance is to make another non-const reference
// but the last declaration in the chain will still violate.
}
void example2()
{
const A const_obj_A(1);
A nonconst_obj_A(2);
ConstA nonconst_obj_constA(3); // violation: used only in const reference
const A& const_ref_A = nonconst_obj_A;
A& nonconst_ref_A = nonconst_obj_A; // violation: no modification using the ref.
const ConstA& const_ref_constA = nonconst_obj_constA;
}
【问题讨论】:
-
它说“变量”,所以我的看法是如果可以引用 const 它应该是。
-
如果您的问题是关于参考的,请提供相关代码和参考。 ...恕我直言,这条规则非常薄弱。