Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Affectations and exceptions

Tags:

c++

exception

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 ?

like image 845
ereOn Avatar asked Oct 28 '10 11:10

ereOn


2 Answers

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.

like image 70
Ferruccio Avatar answered Oct 13 '22 05:10

Ferruccio


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.

like image 42
sharptooth Avatar answered Oct 13 '22 04:10

sharptooth