Affectations and Exceptions

Let's consider that I have the following function:

SomeType createSomeType();

which may throwdepending on some reasons.

Then:

SomeType val = SomeType(); // initial value

try
{
  val = createSomeType(); // here
}
catch (std::exception&)
{
}

If createSomeType()throws, can I always assume that the meaning is val unchanged ?

+5
source share
3 answers

Yes, if createSomeType () throws an exception, the assignment will not happen. The control flow will come from the throw statement, through the destructors of any objects created by createSomeType (), on the stack, and finally, into the catch statement.

+7
source

SomeType , , val , .

createSomeType(), createSomeType() . SomeType , , val "" . SomeType, , .

+1

15.2.1,

Since control passes from the throw expression to the handler, destructors are called for all constructed automatic objects since the try block was introduced. Automatic objects are destroyed in the reverse order of completion of their construction.

Consequently, the value valwill not change ...

0
source

All Articles