简体   繁体   中英

Is it safe to use the throw() suffix on a function containing std::string?

I have a member function that doesn't throw anything so i appended the throw() suffix to the end of it, indicating that it won't throw any exceptions.

My question is, in the function I make use of several std::string , and lets say something goes wrong in the initialization of the std::string , and it throws bad_alloc or out_of_range (or what ever else can go wrong with a std::string).

Is it still safe to still add the throw() suffix?

Herb Sutter says that

exception specifications confer a lot less benefit than they're worth

It can cause more problems than bring benefits. So, you should think twise before doing that.

The exception specification makes a promise about all code which runs inside the function, whether you wrote it or not.

If std::string throws from inside your function, that promise is broken, and your program fails. ( std::unexpected exception, which normally means your program terminates hard)

The throw() specification is proper only if:

  • Nothing your function does can throw, even indirectly

or

  • Your function catches all such exceptions and exits normally (no rethrow).

Two things.

First: the throw() specification add a runtime check that the function does not throw, calling std::unexpected_exception if the promise is broken, which will terminate the program.

Second: throw() is not advised, and has been deprecated in C++11. In C++11 you can use noexcept instead (or the more malleable form noexcept(boolean-expression) ). No runtime check is created, and the behavior is undefined if the function throws.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM