当使用 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&&
。
我的问题是在什么情况下T&&
有用,为什么该方法不返回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;
}