c++ - 如何使 rValue 引用在 RR 获取其值的 try block 之外可用?

标签 c++ c++11 exception-handling move-semantics rvalue-reference

假设我们不想重新设计函数 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/

相关文章:

c++ - 多维数组的划分

java - 在 Java 生产代码中使用 Junit Assert API 可以吗

c++ - catch 站点异常的常见用法是什么?

.net - 为什么 NotImplementedException 存在?

C++ fstream 找不到相对路径

c++ - 为什么 GCC 不能为两个 int32s 的结构生成最佳 operator==?

c++ - QOpenGLWidget : Drawing at 60FPS while not interfering with its existing timing?

C++11模板别名作为模板模板参数导致不同的类型?

C++ 条件变量 cin 和 cout

c++ - 为什么当我试图返回引用时我的对象仍然被复制