与g++ 6.2不同的异常说明符

Different exception specifier with g++ 6.2

本文关键字:异常 说明符 g++      更新时间:2023-10-16

谁能给我解释一下为什么这段代码不能在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);

您使用的是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;

引用链接。

GCC 6中,c++的默认模式已更改为 c++ 14。直到 GCC 5 C + + 98

operator new声明在c++ 11中略有变化。这与抛出异常规范在c++ 11中被弃用以及nothrow声明的引入有关:

  • throw (std::bad_alloc)已省略
  • throw()替换为nothrow
为了获得最佳的向后兼容性,您应该使用-std参数指定您所针对的c++标准,如下所示:
$ g++-6 -std=c++98 wtf.cpp -c