这是一个之前没怎么注意过的细节问题,首先,参加如下代码:
struct MyStruct
{
int type;
char name[40];
};
typedef MyStruct * PMyStruct;
int main(int argc, char * argv[])
{
MyStruct my1{0}, my2{0};
const MyStruct * pmy1 = &my1;
pmy1 = &my2;
const PMyStruct pmy2 = &my1;
pmy2 = &my2;
}
很简单的一段代码,但是全引出了一个不寻常的问题:此段代码编译时,第二个pmy2结构体指针会导致编译器(gcc)报错:“error: assignment of read-only variable ‘pmy2’”,此时如果配合有clang-tidy之类的代码扫描工具,会发现pmy2声明赋值位置提示:“Clang-Tidy: ‘pmy2’ declared with a const-qualified typedef; results in the type being ‘MyStruct *const’ instead of ‘const MyStruct *’”(clang-tidy的misc-misplaced-const)!
Continue reading…