Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try {.... } catch(..) only if a certain compile time expression is true

Here is what we are trying to do

try {
    std::uninitialized_copy(...);
} catch(...) {
    if(!boost::has_trivial_destructor<T>::value) {
       // some cleanup to do here...
    }
    throw;
}

We wonder whether the try/catch has a cost if the compile time constant in the if is false.

Can the compiler within its "as-if" rights remove the try catch and behave as-if the std::uninitialized_copy call appeared without try around it?

Or is there something hidden in the C++ specs that requires the compiler to leave it here? As an example, imagine a hypothetical surrounding_try_blocks() function that returns the dynamic surrounding try blocks count currently around a frame.

like image 945
Johannes Schaub - litb Avatar asked Nov 11 '14 17:11

Johannes Schaub - litb


People also ask

Which statement is true about catch blocks?

catch block is executed only when exception is found. Here divide by zero exception is found hence both catch and finally are executed.

How does try-catch affect performance?

In general, wrapping your Java code with try/catch blocks doesn't have a significant performance impact on your applications. Only when exceptions actually occur is there a negative performance impact, which is due to the lookup the JVM must perform to locate the proper handler for the exception.

What kind of code does the try block of a try-catch statement contain?

The try block includes the code that might generate an exception. The catch block includes the code that is executed when there occurs an exception inside the try block.

How does try-catch finally work in Java?

Try block contains the code that might throw an exception. Catch block contains the exception handler for exceptions in the try block. The finally block contains the critical code that will execute regardless of whether the exception has occurred or not.


1 Answers

I have no idea what the compiler will do but I know that you can enforce the optimization by yourself:

template <class T>
typename boost::enable_if_t<boost::has_trivial_destructor<T>::value, void>
wrap_uninitialized_copy (...) {
    std::uninitialized_copy(...);
}

template <class T>
typename boost::enable_if_t<!boost::has_trivial_destructor<T>::value, void>
wrap_uninitialized_copy (...) {
    try {
        std::uninitialized_copy(...);
    } catch(...) {
        // some cleanup to do here...
        throw;
    }
}
like image 93
Julian Avatar answered Sep 24 '22 01:09

Julian