我有运行时错误,当使用std :: optional替换一些代码时:
旧代码:
T getValue();
...
const auto& value = getValue();
value.get();
Run Code Online (Sandbox Code Playgroud)
新代码:
std::optional<T> getValue();
...
const auto& value = getValue().value();
value.get(); // Runtime error, crash
Run Code Online (Sandbox Code Playgroud)
这对我来说无法预测.崩溃的原因是该方法返回T&&.
我的问题是在哪些情况下T&&可能有用,为什么该方法不返回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;
}
Run Code Online (Sandbox Code Playgroud)