How do I make the rValue reference available outside the try block where the RR gets its value?

Let's say we don't want to redesign a function a_func_that_may_throw

.

try {
    T&& rr = a_func_that_may_throw();
}
catch (const std::exception& e) {
    /* Deal with the exception here. */
}
// Question: How to adapt the code above so as to have `rr` available here?

      

Sorry I didn't ask my question. In (hopefully) the following is added: the question becomes clear.

We can do this with pointers:

T *ptr = nullptr;
try {
    ptr = a_source_that_may_throw();
}
catch (const std::exception& e) {
    /* We know what happened in the try block and can do something without `ptr`. */
}
// `ptr` is available out side the try block.

      

Since C ++ 11, we have an rValue reference on our tool shelves, which saves us from inefficient copying of huge objects returned by existing (possibly bad) functions. Is it possible to take advantage of both, so we don't need to copy and still access the returned object in the same way ptr

used in the above code?

Thank. m (_ _) m

+3


source to share


2 answers


It depends on what you mean by "exception trade". You can do something like this:

T wrap_a_func_that_may_throw() {
  try {
    return a_func_that_may_throw();
  } catch(const std::exception& e) {
    // Do cleanup, logging, etc...
    // May have to re-throw if there is
    // nothing meaningful you can return.... 
  }
  return T()  // Return empty T if possible.
}

Foo&& foo = wrap_a_func_that_may_throw();

      



This gives you the ability to do any specific cleanup, logging, etc., but may need to be re-cast. As Kerrek SB says you still need to have everything using the link in the try block.

+1


source


If the reason you are using an r-value reference is because you need a non const reference bound to a temporary, then IMHO just doesn't bother. Use value semantics instead and let the compiler do the optimization.

T t;
try {
    t = a_func_that_may_throw(); // Compiler can use RVO and move assign to 't'.
} catch (const std::exception& e) {
    /* Deal with the exception here. */
}
// 't' has lifetime until end of scope.

      



An exception would be if T

it is not constructive by default or is assigned movable.

Alternatively, do as @Kerrek SB pointed out in the comments, i.e. move everything into a try block.

+1


source







All Articles