假设我们不想重新设计函数 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?
抱歉没有问清楚我的问题。添加以下内容(希望)使问题更清楚。
我们可以对指针这样做:
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.
自 C++11 起,我们的工具架上就有了 rValue 引用,这使我们免于低效地复制由现有(可能设计不当)函数返回的巨大对象。是否可以同时享受这两个优点,这样我们就不必复制,仍然可以像上面代码中使用 ptr
一样访问返回的对象?
谢谢。 m(_ _)m
最佳答案
如果您使用 r 值引用的原因是您希望将 non const 引用绑定(bind)到临时对象,那么恕我直言,不必费心。而是使用值语义并让编译器进行优化。
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.
异常(exception)情况是 T
不是默认可构造的或可 move 分配的。
或者按照 @Kerrek SB 提到的去做在评论中,即将所有内容 move 到 try block 中。
关于c++ - 如何使 rValue 引用在 RR 获取其值的 try block 之外可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26191311/