I'm writing a little program in C++11 and really use exceptions for one of the first time.
I've got a question about how to catch the exceptions efficiently, and after some googling I still don't have the answer.
Here is the question : What is the more efficient (or recommended) between catching the exception by (const?) lvalue reference, or by (const?) rvalue reference?
In code this give :
1)
try { throw std::exception{"what"}; }
catch (std::exception& ex) {}
2)
try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}
3)
try { throw std::exception{"what"}; }
catch (std::exception&& ex) {}
4)
try { throw std::exception{"what"}; }
catch (const std::exception&& ex) {}
You should catch by const lvalue reference (2):
try { throw std::exception{"what"}; }
catch (const std::exception& ex) {}
Rationale:
In C++11 it is possible (via use of shared_future
) that two threads could be unwinding the same exception at the same time. This can happen in your code even if you are not aware of shared_future
being used, unless you control the entire application.
If two threads are caught unwinding the same exception simultaneously, and one or both of the threads modifies the exception, then you've got a race condition.
So as long as you don't have to modify the exception object in the catch clause, let the compiler enforce that policy for you - catch by const&
. If you really do need to modify the exception, then make a copy of it, modify the copy and throw the copy. You can do this by catching by value if you are sure this won't slice your exception object (which is not usually the case if you are catching std::exception
).
I suppose that exception should be caught in usual manner by lvalue-reference. Here's good explanation of rvalues-references use
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With