【问题标题】:Different exception specifier with g++ 6.2与 g++ 6.2 不同的异常说明符
【发布时间】:2016-08-28 07:23:21
【问题描述】:

有人能解释一下为什么这段代码不能用 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++ exception g++ throw


    【解决方案1】:

    您使用的是 C++11 或更高版本吗?

    C++98 中原始的 operator 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;
    

    Reference link.

    【讨论】:

    • 通过添加-std=c++03,g++ 可以正常编译。但这并不能解释为什么我会收到此错误消息,对吧?我认为wtf.cpp 的第 3 行仍然具有与第 4 行相同的异常说明符。
    • @BigDawg - throw()noexcept 有类似的效果,但throw (std::bad_alloc) 与不指定抛出的异常完全不同。
    【解决方案2】:

    GCC 6 中,C++ 的默认模式有 changedC++14。在 GCC 5 之前它是 C++98

    operator new 声明在 C++11 中略有变化。这与抛出异常规范为deprecated in C++11,以及nothrow 声明的引入有关:

    • throw (std::bad_alloc) 已省略
    • throw() 替换为 nothrow

    为了获得最佳的向后兼容性,您应该使用 -std 参数指定您所针对的 C++ 标准,如下所示:

    $ g++-6 -std=c++98 wtf.cpp -c 
    

    【讨论】:

      猜你喜欢
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2021-11-11
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      相关资源
      最近更新 更多