【发布时间】:2014-01-27 10:30:35
【问题描述】:
这是我的代码的一部分...
正如我在下面所做的那样,我知道铸造是正确的,但我收到了我的逻辑的 linting 警告.. 你能解释一下为什么会这样吗..
我的部分代码:
typedef struct
{
char appid[4]; /**< application id */
int32 pid; /**< process id of user application */
} DApplication;
static int32 d_cmp(const void *m1, const void *m2)
{
DApplication *mi1 = (DApplication *) m1; //Line 1
DApplication *mi2 = (DApplication *) m2; //Line 2
return memcmp(mi1->appid, mi2->appid, 4); //Line 3
}
And warnings are :
Sample.cpp (line 1):Note 960: Violates MISRA 2004 Required Rule 11.5, attempt to cast away const/volatile from a pointer or reference
Sample.cpp (line 2):Note 960: Violates MISRA 2004 Required Rule 11.5, attempt to cast away const/volatile from a pointer or reference
Sample.cpp (line 3):Note 960: Violates MISRA 2004 Required Rule 10.1, Implicit conversion changes signedness
...Courtsey MISRA
As per the MISRA rule : Rule 11.5 (required): A cast shall not be performed that removes any const or volatile
qualification from the type addressed by a pointer.
[Undefined 39, 40]
Any attempt to remove the qualification associated with the addressed type by using casting is a
violation of the principle of type qualification. Notice that the qualification referred to here is not
the same as any qualification that may be applied to the pointer itself.
uint16_t x;
uint16_t * const cpi = &x; /* const pointer */
uint16_t * const * pcpi; /* pointer to const pointer */
const uint16_t * * ppci; /* pointer to pointer to const */
uint16_t * * ppi;
const uint16_t * pci; /* pointer to const */
volatile uint16_t * pvi; /* pointer to volatile */
uint16_t * pi;
...
pi = cpi; /* Compliant - no conversion
no cast required */
pi = (uint16_t *)pci; /* Not compliant */
pi = (uint16_t *)pvi; /* Not compliant */
ppi = (uint16_t * *)pcpi; /* Not compliant */
ppi = (uint16_t * *)ppci; /* Not compliant */
SO According to this rule i think it is fine
【问题讨论】:
-
为什么你认为选角合适?你正在抛弃
const。 -
void*这不是真正的C++=) -
那么正确的投射方式是什么??
-
铸造将是
const DApplication *mi1 = reinterpret_cast<const DApplication*> m1;。但这仍然不是正确的 C++。 -
@Ashwin 如果您确定
m1和m2实际上指向非 const 对象,则应将函数参数指定为void *,而不是const void *。而且,另一个大问题当然是你为什么要使用void...(但这与 constness 问题无关)。