c++ - C++ 中的内联 throw() 方法

标签 c++ gcc throw

我正在尝试定义一个非常简单的异常类。因为它太简单了,所以我只想将它保留在 .h 文件中,但编译器不喜欢 throw()。代码:

#include <exception>
#include <string>

class PricingException : public virtual std::exception
{
private:
    std::string msg;
public:
        PricingException(std::string message) : msg(message) {}
        const char* what() const throw() { return msg.c_str(); }
        ~PricingException() throw() {}
};

GCC 给出以下错误:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:13: error: expected unqualified-id before ‘{’ token
/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: expected unqualified-id before ‘{’ token

对于带有 throw() 的行。知道如何解决吗?

编辑

我试图删除有问题的方法的主体,即

virtual ~PricingException() throw();// {}

现在我收到更奇怪的错误消息:

/home/ga/dev/CppGroup/MonteCarlo/PricingException.h:14: error: looser throw specifier for ‘virtual PricingException::~PricingException()’
/usr/include/c++/4.5/exception:65: error:   overriding ‘virtual std::exception::~exception() throw ()’

它只是忽略了我的抛出说明符!

最佳答案

尝试使用 C++0x 语法,g++ 4.5 可能足够新以支持它:

const char* what() const noexcept { return msg.c_str(); }

但是,这无关紧要(3242 草案的措辞,[except.spec] 部分:

Two exception-specifications are compatible if:

  • both are non-throwing (see below), regardless of their form,
  • both have the form noexcept(constant-expression) and the constant-expressions are equivalent,
  • one exception-specification is a noexcept-specification allowing all exceptions and the other is of the form throw(type-id-list), or
  • both are dynamic-exception-specifications that have the same set of adjusted types.

.

If a virtual function has an exception-specification, all declarations, including the definition, of any function that overrides that virtual function in any derived class shall only allow exceptions that are allowed by the exception-specification of the base class virtual function.

.

A function with no exception-specification or with an exception-specification of the form noexcept(constant-expression) where the constant-expression yields false allows all exceptions. An exception-specification is non-throwing if it is of the form throw(), noexcept, or noexcept(constant-expression) where the constant-expression yields true. A function with a non-throwing exception-specification does not allow any exceptions.

因此请尝试更新的 g++ 版本,这些更改可能会更完整地实现。

关于c++ - C++ 中的内联 throw() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5472801/

相关文章:

c++ - 人们会推荐哪些工具来查看 gcc/linux 目标文件?

python - fatal error : Python. h : No such file or directory, python-Levenshtein 安装

java - java中从Exception类抛出异常

c++ - Q_UNUSED 相对于省略参数名称有什么好处?

c++ - nghttp2 asio 连接到 Apple 推送通知超时

c++ - std::make_array 的目的是什么? C++20 中还需要它吗?

c++ - cout 是同步的/线程安全的吗?

meteor - throw Meteor.Error总是在error.error中返回403

swift - 为什么 'throws' 在 Swift 中不是类型安全的?

javascript - 如何将字符串值从 C++ 返回到 javascript (windows/Visual studio 2008)?