How to deal with noexcept in Visual Studio

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();
    }
};

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

error: looser throw specifier for 'virtual const char* UserException::what() const'

So I add noexcept :

virtual const char* what() const noexcept override

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

error C3646: 'noexcept' : unknown override specifier

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 .


Use a macro

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

And then define the function as

virtual const char* what() const NOEXCEPT override

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.


"noexcept" is only supported since the Visual Studio 2015 (as stated here: https://msdn.microsoft.com/en-us/library/wfa0edys.aspx). I have used following code with Visual Studio 2013 (derived from above examples):

#if !defined(HAS_NOEXCEPT)
#if defined(__clang__)
#if __has_feature(cxx_noexcept)
#define HAS_NOEXCEPT
#endif
#else
#if defined(__GXX_EXPERIMENTAL_CXX0X__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 46 || 
    defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 190023026
#define HAS_NOEXCEPT
#endif
#endif

#ifdef HAS_NOEXCEPT
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif

This check works to see if noexcept is supported:

// Is noexcept supported?
#if defined(__clang__) && __has_feature(cxx_noexcept) || 
    defined(__GXX_EXPERIMENTAL_CXX0X__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 46 || 
    defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 180021114
#  define NOEXCEPT noexcept
#else
#  define NOEXCEPT
#endif

The above works with Clang, GCC and MSVC.

链接地址: http://www.djcxy.com/p/27924.html

上一篇: 嘲讽boto3 S3客户端方法Python

下一篇: 如何在Visual Studio中处理noexcept