有人可以向我解释为什么这段代码不能用g ++版本6.2.0编译,但是使用clang ++版本3.9.0-svn274438-1和icpc版本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);
答案 0 :(得分:5)
您使用的是C ++ 11或更高版本吗?
C ++ 98中的原始运算符new()声明
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();
在C ++ 11中已更改为使用 noexcept 关键字:
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;
答案 1 :(得分:1)
在 GCC 6 中,C ++的默认模式有changed到 C ++ 14 。在 GCC 5 之前, C ++ 98 。
{+ 1}}声明在C ++ 11中略有改变。它与抛出异常规范为deprecated in C++11以及引入operator new
声明这一事实有关:
nothrow
已被省略throw (std::bad_alloc)
已替换为throw()
为了获得最佳的向后兼容性,您应该使用nothrow
参数指定您要定位的C ++标准,如下所示:
-std