| 915 | |
| 916 | # Test taking address of casts (runtime/casting) |
| 917 | def testRuntimeCasting(self): |
| 918 | error_msg = ( |
| 919 | "Are you taking an address of a cast? " |
| 920 | "This is dangerous: could be a temp var. " |
| 921 | "Take the address before doing the cast, rather than after" |
| 922 | " [runtime/casting] [4]" |
| 923 | ) |
| 924 | self.TestLint("int* x = &static_cast<int*>(foo);", error_msg) |
| 925 | self.TestLint("int* x = &reinterpret_cast<int *>(foo);", error_msg) |
| 926 | self.TestLint( |
| 927 | "int* x = &(int*)foo;", |
| 928 | [ |
| 929 | "Using C-style cast. Use reinterpret_cast<int*>(...) " |
| 930 | "instead [readability/casting] [4]", |
| 931 | error_msg, |
| 932 | ], |
| 933 | ) |
| 934 | self.TestLint("BudgetBuckets&(BudgetWinHistory::*BucketFn)(void) const;", "") |
| 935 | self.TestLint("&(*func_ptr)(arg)", "") |
| 936 | self.TestLint("Compute(arg, &(*func_ptr)(i, j));", "") |
| 937 | |
| 938 | # Alternative error message |
| 939 | alt_error_msg = ( |
| 940 | "Are you taking an address of something dereferenced " |
| 941 | "from a cast? Wrapping the dereferenced expression in " |
| 942 | "parentheses will make the binding more obvious" |
| 943 | " [readability/casting] [4]" |
| 944 | ) |
| 945 | self.TestLint("int* x = &down_cast<Obj*>(obj)->member_;", alt_error_msg) |
| 946 | self.TestLint("int* x = &down_cast<Obj*>(obj)[index];", alt_error_msg) |
| 947 | self.TestLint("int* x = &(down_cast<Obj*>(obj)->member_);", "") |
| 948 | self.TestLint("int* x = &(down_cast<Obj*>(obj)[index]);", "") |
| 949 | self.TestLint("int* x = &down_cast<Obj*>(obj)\n->member_;", alt_error_msg) |
| 950 | self.TestLint("int* x = &(down_cast<Obj*>(obj)\n->member_);", "") |
| 951 | |
| 952 | # It's OK to cast an address. |
| 953 | self.TestLint("int* x = reinterpret_cast<int *>(&foo);", "") |
| 954 | |
| 955 | # Function pointers returning references should not be confused |
| 956 | # with taking address of old-style casts. |
| 957 | self.TestLint("auto x = implicit_cast<string &(*)(int)>(&foo);", "") |
| 958 | |
| 959 | def testRuntimeSelfinit(self): |
| 960 | self.TestLint( |