本文介绍了如何在Visual Studio中处理noexcept的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个自定义异常,派生自 std :: exception 并覆盖 what() 。起初,我写的是这样:

I'm trying to create a custom exception that derives from std::exception and overrides what(). At first, I wrote it like this:

class UserException : public std::exception
{
private:
    const std::string message;
public:
    UserException(const std::string &message)
        : message(message)
    {}

    virtual const char* what() const override
    {
        return message.c_str();
    }
};

这在VS2012中可以正常工作,但它不能在GCC 4.8中用 -std = c ++ 11

This works fine in VS2012, but it doesn't compile in GCC 4.8 with -std=c++11:

所以我添加 noexcept p>

So I add noexcept:

virtual const char* what() const noexcept override

这在GCC中工作正常,但它不能在Visual Studio中编译(因为VS 2012不支持 noexcept ):

This works fine in GCC, but it doesn't compile in Visual Studio (because VS 2012 doesn't support noexcept):

什么是处理这个的推荐方法?我想使用两个编译器编译相同的代码,我使用C ++ 11功能,所以我不能用不同的 -std 编译。

What is the recommended way to deal with this? I want the same code to compile with both compilers and I'm using C++11 features, so I can't compile with different -std.

推荐答案

使用宏

#ifndef _MSC_VER
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif

然后将函数定义为

virtual const char* what() const NOEXCEPT override

您也可以修改,以允许 noexcept VS通过检查 _MSC_VER 的值;对于VS2012,值为1600.

You could also modify that to allow noexcept on later versions of VS by checking the value of _MSC_VER; for VS2012 the value is 1600.

这篇关于如何在Visual Studio中处理noexcept的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 10:29