我有運行時錯誤,當使用的std ::可選更換了一些代碼:爲什麼std :: optional :: value()&&;返回&&?
舊代碼:
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;
}
請**您的問題與[mcve]或[SSCCE(Short,Self Contained,Correct Example)](http://sscce.org) – NathanOliver
此外,[this](https:/ /stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope)可能是相關的,如果你正在返回一個參考。 – NathanOliver
如果它返回'/ * const */T&'BTW,你會遇到類似的問題。 – Jarod42