Home > OS >  Throw when reassigning
Throw when reassigning

Time:07-28

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)
{
    //...
}

CodePudding user response:

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.

CodePudding user response:

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.

  • Related