Search code examples
c++exception-safety

Throw when reassigning


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

Solution

  • 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.