在Scott Schurr 在CppCon上的"介绍constexpr"演讲的最后,他问"有没有办法毒害一个功能"?然后他解释说,这可以通过以下方式完成(尽管以非标准方式):
throw在constexpr功能extern const char*extern的throw我觉得我有点超出我的深度,但我很好奇:
函数中毒在C++中是非常有用的技术.
一般来说,它指的是使函数不可用,例如,如果你想禁止在程序中使用动态分配,你可能会"毒害" malloc函数,因此无法使用它."中毒"标识符意味着"中毒"后对标识符的任何引用都是硬编译器错误
例如(在此处查看现场演示)
#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);
}
Run Code Online (Sandbox Code Playgroud)
我发现这种技术对于防止在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
}
Run Code Online (Sandbox Code Playgroud)
这也可以在C中用来防止使用C++关键字,因为C++有很多关键字而不是C&C使用C++特定关键字作为C中的标识符是完全有效的.
例如(在此处 …