如何在 VC++ 中毒化标识符? [英] How to poison an identifier in VC++?
问题描述
函数中毒是 C++ 中非常有用的技术.
Function poisoning is very useful technique in C++.
一般来说,它指的是使功能无法使用,例如如果您想禁止在程序中使用动态分配,您可以毒化" malloc 函数使其无法使用.'中毒'一个标识符意味着在'中毒'之后对标识符的任何引用都是一个硬编译器错误
In general it refers to making a function unusable, e.g. if you want to ban the use of dynamic allocation in a program you could "poison" the malloc function so it can't be used. 'Poisoning' an identifier means that any reference to the identifier after the 'poisoning' is a hard compiler error
例如(查看现场演示这里)
#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);
}
我发现这种技术对于防止在 C++ 中滥用保留字非常有用.
I found this technique very useful to prevent misuse of reserved words in C++.
例如:
#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
}
这也可以用在 C 中,防止使用 C++ 关键字,因为 C++ 的关键字比 C &在 C 中使用 C++ 特定关键字作为标识符是完全有效的.
This can also be used in C to prevent the use of C++ keywords because C++ has many keywords than C & it is perfectly valid to use C++ specific keywords as an identifier in C.
例如(查看现场演示这里)
#include <stdio.h>
#pragma GCC poison new
int main(void)
{
int new=5; // oops compiler error use of poisoned identifer new.
printf("%d",new);
}
但是要使用这种中毒,我们需要使用实现定义的 pragma 指令.幸运的是,clang & 重新识别了 GCC 编译指示.也很好用.但是,如果我有 VC++ 编译器(Microsoft Visual Studio),则需要哪种编译指示.如何在 VC++ 编译器中执行此操作?
But to use this poisoning we need to use the pragma directive which is implementation defined. Fortunately the GCC pragma reconginized by clang & also works nicely. But which pragma is needed If I 've VC++ compiler (Microsoft Visual studio). How to do this in VC++ compiler?
推荐答案
MSVC++ 有两种方法可以做到这一点.要获得 GCC 版本,您可以使用 #pragma deprecated.这会产生警告 C4995,您可以使用/WX 将其转换为错误.
MSVC++ has two ways to do this. To get the GCC version you'd use #pragma deprecated. That produces warning C4995, you can turn that into an error with /WX.
然而,这会使任何具有您指定名称的标识符中毒,它的选择性不足以防止对碰巧具有相同标识符名称的 C++ 成员发出警告.例如,您不能使用它来弃用特定的函数重载.通过第二种方式解决,__declspec(deprecated).
That however poisons any identifier with the name you specified, it isn't selective enough to prevent warnings on C++ members that happen to have the same identifier name. You couldn't use it to deprecate a specific function overload for example. Solved by the second way, __declspec(deprecated).
一般来说,您更喜欢后者以避免意外匹配.但是请注意它有一个先有鸡还是先有蛋的问题,您只能弃用编译器知道的函数.强迫您,例如,#include 一个您根本不想使用的标头.
In general you'd prefer the latter to avoid accidental matches. But do beware that it has a chicken-and-egg problem, you can only deprecate a function that the compiler knows about. Forcing you to, say, #include a header that you don't want to use at all.
这篇关于如何在 VC++ 中毒化标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!