Consider:
template <typename T>
struct S
{
auto Value() const
{
return value;
}
T value;
};
Can Value()
ever throw an exception? Why or why not? If not, is it safe to mark this method as noexcept
?
What I fundamentally don't understand is whether return value;
is something that can ever throw an exception.
Value()
might throw an exception and therefore you should not mark it as noexcept
.
This might happen since Value()
returns a T
object by value.
This means a copy will be made and the copy constructor of T
might throw. The compiler will generate the copy istructions in the method body.
Copy-ellision is not relevant because value
is a member, not a local or a temporary.
But even if was relevant, it does not change that.
The content of the value
member would anyway to be copied (or moved) into the target object that called the method. This would be done by way of executing the relevant constructor of T
- copy or move - or assignment operator which might throw.
It does not matter if the return value is actually assigned to a variable, as you can see in the demo below.