为什么选择std :: optional :: value()&&amp ;;返回&&amp ;? [英] Why std::optional::value() &&; return &&?

查看:175
本文介绍了为什么选择std :: optional :: value()&&amp ;;返回&&amp ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用std :: optional替换某些代码时,我遇到了运行时错误

I have had runtime error, when replaced some code by using std::optional:

旧代码:

T getValue();
...
const auto& value = getValue();
value.get();

新代码:

std::optional<T> getValue();
...
const auto& value = getValue().value();
value.get(); // Runtime error, crash 

对我来说这是不可预测的. 崩溃的原因是该方法返回T&&.

It was unpredictable for me. The reason of crash is that the method returns T&&.

我的问题是T&&在什么情况下有用,为什么该方法不返回T.

My question is in what cases T&& can be useful, why the method does not return a T.

完整代码:

#include <experimental/optional>
#include <iostream>
#include <memory>

struct Value {
    std::unique_ptr<int> a = std::make_unique<int>(5);
};

std::experimental::optional<Value> getValue() {
    Value v;
    return v;
}

int main() {
    const Value& value = getValue().value();
    std::cout << *value.a << std::endl;
    return 0;
}

推荐答案

这是由两个相互竞争的需求引起的较小的设计缺陷.

It is a minor design flaw caused by two competing needs.

首先,避免多余的动作,其次,使参考寿命得以延长.

First, avoiding extra moves, and second enabling reference lifetime extension.

这两个在当前的C ++中竞争;您通常无法一次解决两个问题.因此,您将很偶然地看到代码在做另一件事.

These two compete in current C++; you usually cannot solve both problems at once. So you will see code doing one or the other, quite haphazardly.

我个人发现返回一个右值引用比从一个即将被销毁的对象转移产生更多的问题,但是标准化std::optional的人则不同意.

I personally find returning an rvalue reference to generate more problems than moving from a soon to be destroyed object, but those who standardized std::optional disagreed.

我首选的解决方案还有其他缺点.

My preferred solution would have other downsides.

要解决此问题(不必做出这些让步),我们将需要对寿命延长的工作原理进行复杂的混乱的重新定义.因此,我们必须暂时解决这些问题.

To fix this—to not have to make these compromises—we would require a complex messy redefinition of how lifetime extension works. So we have to live with these problems for now.

这篇关于为什么选择std :: optional :: value()&amp;&amp ;;返回&amp;&amp ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆