I’m currently trying to get my head around noexcept (like almost everyone I avoided the old “runtime exception specification”). Whilst I think I get the basic idea of noexcept, I’m not sure what happens in a situation like:
class sample {
public:
sample() noexcept { }//this doesn't throw
sample(const sample & s) noexcept { }
sample(sample && s) noexcept { }
sample & operator=(const sample & s) noexcept {...}
sample & operator=(sample && s) noexcept { ... }
~sample() noexcept() { }//this should never ever throw
sample operator-() const { return *this * -1; }//assuming that there is a operator*…
sample & operator*=(const sample & s) noexcept { ... }
};
sample operator*(sample s1, const sample & s2) { return s1 *= s2; }//same problem as with operator-…
Is it safe to declar sample::operator- as noexcept, or not? (considering that it’s calling a constructor on return)
EDIT: I updated the code section as it seems that the central part of the question was not clear…
After the edit: Your implementation of
operator-is guaranteed not to throw any exception (well, at least if you markoperator*asnoexcept, that is), and it is thus safe to mark it asnoexcept. I don’t really understand your concern, though so I might be missing the reason for the question. All of the operations, including the potential copy or move construction are explicitly markednoexcept… where is the issue?Unless you explicitly mark it as
noexceptit will not have that qualification. Now, depending on the implementation ofoperator*and the copy-constructor it might actually never throw, but that does not make itnoexcept.As of the copy-constructor, if you don’t define it, the implicitly declared copy constructor will be
noexceptor not depending on whether all the members of your type arenoexcept(again, not only that they don’t throw, but that they have that qualification)