enforce std::nothrow at compile time or during static analysis

189 views Asked by At

Is it possible to enforce the use of operator new strictly with std::nothrow at compile time or at least during static analysis using pc-lint? Using c++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9) compiler.

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Yes, it's possible. GCC supports the error attribute, which makes any use of a particular function a hard error. Applying this to operator new has the expected effect.

#include <cstddef>

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

int main() {
  new int;
}

This is rejected by the compiler with:

h.cc: In function ‘int main()’:
h.cc:6:10: error: call to ‘operator new’ declared with attribute error: use new(std::nothrow) instead
   new int;
          ^

Do note however that this applies only to code in which this custom declaration is visible. You may want to check the code of any libraries you use, including the standard library.