How to poison an identifier in VC ++?

Function poisoning is a very useful method in C ++.

In general, this refers to making the function unusable, for example. if you want to prohibit the use of dynamic allocation in the program, you can "poison" the malloc function so that it cannot be used. "Poisoning" identifier means that any reference to an identifier after "poisoning" is a hard compiler error

For example (see live demo here )

#include <iostream> #include <cstdlib> #pragma GCC poison malloc int main() { int* p=(int*)malloc(sizeof(int)); // compiler error use of poisoned function malloc *p=3; std::cout<<*p<<'\n'; free(p); } 

I found this technique very useful for preventing abuse of reserved words in C ++.

For example:

 #include "test.h" // contains definition of some class T #pragma GCC poison private #define private public // oops compiler error use of poisoned identifier private in macro int main() { // Instantiate T & use it members } 

It can also be used in C to prevent the use of C ++ keywords, because C ++ has many keywords than C, and it is perfectly acceptable to use C ++ keywords as an identifier in C.

For example (see live demo here )

 #include <stdio.h> #pragma GCC poison new int main(void) { int new=5; // oops compiler error use of poisoned identifer new. printf("%d",new); } 

But to use this poisoning, we need to use the pragma directive, which is defined by the implementation. Fortunately, the GCC pragma reconginized clang also works great. But what pragma is needed if I am a compiler of VC ++ (Microsoft Visual studio). How to do it in the VC ++ compiler?

+5
c ++ visual-c ++ preprocessor-directive pragma
source share
1 answer

MSVC ++ has two ways to do this. To get the GCC version, you must use # pragma obsolete . This gives warning C4995, you can turn this into an error with / WX.

However, it poisons any identifier with the name you specify, it is not selective enough to prevent warnings on C ++ members that have the same identifier name. You could not use it to refuse a specific function overload, for example. Solved by the second method, __ declspec (deprecated) .

In general, you would prefer the latter to avoid random matches. But be careful that it has a problem with the chicken and the egg, you can only refuse the function that the compiler knows about. Making you, say, # include a headline that you don't want to use at all.

+7
source share

All Articles