Different exception specifier with g++ 6.2

BigDawg picture BigDawg · Aug 28, 2016 · Viewed 7.2k times · Source

Could someone explain to me why this code doesn't compile with g++ version 6.2.0, but compiles fine with clang++ version 3.9.0-svn274438-1 and icpc version 16.0.2

$ cat wtf.cpp
#include <cstdio>
#include <new>
void *operator new(std::size_t) throw(std::bad_alloc);
void *operator new(std::size_t) throw (std::bad_alloc) { void *p; return p; }

$ g++-6 wtf.cpp -c 
wtf.cpp: In function ‘void* operator new(std::size_t)’:
wtf.cpp:4:7: error: declaration of ‘void* operator new(std::size_t) throw (std::bad_alloc)’ has a different exception specifier
 void *operator new(std::size_t) throw (std::bad_alloc) { void * p; return p; }
       ^~~~~~~~
wtf.cpp:3:7: note: from previous declaration ‘void* operator new(std::size_t)’
 void *operator new(std::size_t) throw(std::bad_alloc);

Answer

Palec picture Palec · Aug 28, 2016

Are you using C++11 or later?

The original operator new() declarations in C++98

throwing:   
void* operator new (std::size_t size) throw (std::bad_alloc);

nothrow:
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) throw();

placement:
void* operator new (std::size_t size, void* ptr) throw();

Have been changed in C++11 to use noexcept keyword:

throwing:   
void* operator new (std::size_t size);

nothrow:    
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;

placement:  
void* operator new (std::size_t size, void* ptr) noexcept;

Reference link.