1

是否可以在编译时或至少在使用 pc-lint 的静态分析期间new严格强制使用运算符?std::nothrow使用 c++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9) 编译器。

4

1 回答 1

2

是的,这是可能的。GCC 支持该error属性,这使得对特定函数的任何使用都成为硬错误。应用它operator new有预期的效果。

#include <cstddef>

void *operator new(std::size_t) __attribute__((error("use new(std::nothrow) instead")));

int main() {
  new int;
}

这被编译器拒绝:

h.cc:在函数'int main()'中:
h.cc:6:10:错误:调用带有属性错误声明的“operator new”:改用 new(std::nothrow)
   新的整数;
          ^

但是请注意,这仅适用于此自定义声明可见的代码。您可能想要检查您使用的任何库的代码,包括标准库。

于 2015-06-22T08:31:17.363 回答