【发布时间】:2014-10-04 09:07:11
【问题描述】:
假设我们不想重新设计函数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
【问题讨论】:
-
如果该函数确实抛出,
rr未定义。为什么您希望能够引用它? -
其他方式:将需要引用的所有内容移入 try 块。
-
如果函数抛出异常,我们当然会知道,我们可以在 catch-block 中优雅地结束进程。
-
@Mat OP 不会尝试在抛出时引用它,如果它没有抛出,他会尝试引用它。
-
@Cody:不是一切,只是需要参考的一切。如果这太大而无法解释,请重构您的代码。
标签: c++ c++11 exception-handling move-semantics rvalue-reference