Throw when reassigning

58 views Asked by At
try
{
    object = mayThrow();
}
catch (const std::exception& exc)
{
    //...
}

If mayThrow() actually throws, will the original object be untouched? Or is it better to do it this way?

try
{
    Object newObject = mayThrow();
    object = std::move(newObject);
}
catch (const std::exception& exc)
{
    //...
}
2

There are 2 answers

0
Aykhan Hagverdili On BEST ANSWER

Unless mayThrow() has direct access to object and does some monkeying within, the final assignment happens if and only if mayThrow() returns successfully and the object stays unchanged otherwise.

0
user12002570 On

If mayThrow() actually throws, will the original object be untouched?

Yes, object is unchanged if/when mYThrow throws(assuming myThrow has no connection internally with object and do not affect object in any way).

For example, say object is of some class-type then the body of the copy assignment operator will be entered only when myThrow succeeds. In other words, in this case object will be left unchanged.