Lets consider I have the following function:
SomeType createSomeType();
which can throw
depending on some reasons.
Then:
SomeType val = SomeType(); // initial value
try
{
val = createSomeType(); // here
}
catch (std::exception&)
{
}
If createSomeType()
throws, can I always assume that val
value is unchanged ?
Yes, if createSomeType() throws an exception, the assignment will not happen. The flow of control will go from the throw statement, through the destructors of any objects createSomeType() has on the stack and finally to the catch statement.
If the assignment operator for SomeType
is exception-safe then you can be sure that either val
will be assigned a consistent new value or its initial value will remain unchanged.
However the exception might be thrown by either createSomeType()
or by the assignment after createSomeType()
runs successfully. If the assignment operator for SomeType
is overloaded and it can throw exceptions it might happen that val
ends up in "half-assigned" inconsistent state. The latter is a result of not adopting exception safety in SomeType
design which is bad but still can happen.
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