Should I use noexcept method modifier for getters always in C++11?
I mean simple getters here that just return members. At least in all my getters I have here an exception can't possibly be thrown. One downside is that a getter gets too verbose:
const std::string& getName() const noexcept{ return name; }
The good side as pointed out in Stroustrup's book is that the compiler might do some optimizations here and there.
E. 12: Use noexcept when exiting a function because of a throw is impossible or unacceptable. you don't care in case of an exception. You are willing to crash the program because you can not handle an exception such as std::bad_alloc due to memory exhaustion.
Never. noexcept is for compiler performance optimizations in the same way that const is for compiler performance optimizations. That is, almost never. noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception.
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.
"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.
noexcept
is a promise that is very hard to take back. For example, you could later do something as simple as change the return type to std::string
(for whatever reason), but because that needs to allocate a copy of the string, it can throw.
So the standard went the way of "add noexcept
only when it's necessary or highly beneficial", and I think that's a good rule to follow. The question you need to ask yourself is, will the callers of this method need it to not throw?
If there is a good chance that someone needs this noexcept qualifier, I would add it. If you do not add it, you have more possibilities to change the implementation (remember, this is the usual argument for setter/getter [and I'm not a fan of setter and getters]).
You usually need this "no throw" guaranty, if you need to call this function in a "rollback, recover from error" situation. For example if you want to call it from a destructor then your life is easier if it offers the nothrow guarantee (and noexcept is the modern way of offering that).
So, I wouldn't make a general rule to add it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With