Let's say I have the following code:
class A {
public:
void SetInteger(const int val) noexcept { integerMember = val; }
void SetString(const std::string& val) { stringMember = val; }
int GetInteger() const noexcept { return integerMember; }
std::string GetString() const { return stringMember; }
private:
int integerMember;
std::string stringMember;
}
Using noexcept
for integral types and pointers seems for me pretty obvious.
But what are recommendations in case of not integral types like classes and structures that do not throw exceptions in constructor/copy-constructor and constructors of their parts explicitly (meaning using throw
in constructor body)?
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.
noexcept is primarily used to allow "you" to detect at compile-time if a function can throw an exception. Remember: most compilers don't emit special code for exceptions unless it actually throws something.
If an exception is not supposed to be thrown, the program cannot be assumed to cope with the error and should be terminated as soon as possible. Declaring a function noexcept helps optimizers by reducing the number of alternative execution paths. It also speeds up the exit after failure.
C26440 DECLARE_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.
You should avoid noexcept
specifiers for functions which may throw (unless you're prepared to have your code call std::terminate()
). Explicit throw
specifiers are deprecated, so don't rely on them, rather use the noexcept
operator. For example
template<typename T>
class Foo
{
T m_datum;
public:
Foo& SetDatum(T const&x) noexcept(noexcept(m_datum=x))
{
m_datum = x;
return *this;
}
};
Outside of special member functions, noexcept
is not that useful. But if you want it:
void SetString(const std::string& val)
noexcept(std::is_nothrow_copy_assignable<std::string>::value) {
}
First way for getter:
const std::string& GetString() const noexcept {return stringMember; }
Second way is for setter:
void SetString(std::string&& val) noexcept {
swap(stringMember, val);
}
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