Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
svick Avatar asked Aug 22 '13 17:08

svick


People also ask

Does Noexcept make code faster?

That noexcept keyword is tricky, but just know that if you use it, your coding world will spin faster.

Should I use Noexcept?

There are two good reasons for the use of noexcept: First, an exception specifier documents the behaviour of the function. If a function is specified as noexcept, it can be safely used in a non-throwing function. Second, it is an optimisation opportunity for the compiler.

What does Noexcept mean?

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.

Can be declared Noexcept?

"Function can be declared 'noexcept'." If code is not supposed to cause any exceptions, it should be marked as such by using the 'noexcept' specifier. This would help to simplify error handling on the client code side, as well as enable compiler to do additional optimizations.


1 Answers

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.

like image 188
Praetorian Avatar answered Sep 22 '22 09:09

Praetorian