☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

类型转换不应去掉 const、volatile 等属性

12.8 ID_qualifierCastedAway
目录 › next › previous

去掉 const、volatile 等属性会使相关机制失去意义,往往意味着设计上的缺陷,也会导致标准未定义的行为。

示例:

const int c = 1;
volatile int v = 2;

*(int*)&c = 3;   // Non-compliant, undefined behavior
*(int*)&v = 4;   // Non-compliant, undefined behavior

通过去掉 const 或 volatile 的转换修改相关对象会导致标准未定义的行为。

又如:

struct A {
    void foo() const {
        const_cast<A*>(this)->n++;   // Non-compliant
        ....
    }
private:
    int n = 0;
};

例中 foo 为常量成员函数,用 const_cast 去掉 this 指针的 const 限定是不符合要求的。

如果成员的改变只起辅助作用而不影响对象状态,可将成员设为 mutable,否则应重新设计类,如:

struct A {
    void foo() const {
        n++;             // OK
        ....
    }
private:
    mutable int n = 0;   // Can be modified by const member functions
};

依据

ISO/IEC 9899:1999 6.7.3(5)-undefined ISO/IEC 9899:2011 6.7.3(6)-undefined ISO/IEC 14882:2003 7.1.5.1(4 7)-undefined ISO/IEC 14882:2011 7.1.6.1(4 6)-undefined

参考

C++ Core Guidelines ES.50 MISRA C 2004 11.5 MISRA C 2012 11.8 MISRA C++ 2008 5-2-5 SEI CERT EXP32-C SEI CERT EXP55-CPP
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.