표준 : 옵션을 사용하여 몇 가지 코드를 교체 할 때 내가 런타임 오류가 있었다 :왜 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
을 반환하지 않습니다.
전체 코드 :
(rvalue-) 참조를 반환하는 것이 더 비용이없는 반면, 그것을 구성 이동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