Assume we have a function which returns std::optional<A>
. Then what is a proper way of using the result in the range-based for loop? The easiest way does not work:
for (auto&& e : a().value()) {
// ^--- A&& is returned, so A is destructed
// before loop starts
This issue would not exist if we would had T optional::value() &&
instead of T&& optional::value() &&
, but both STL and Boost define it in a second way.
What is a proper way of handling this situation? I don't like both solutions that I could think of (sandbox):
std::experimental::optional<A> a() {
// ...
}
void ok1() {
// ugly if type of A is huge
for (auto&& e : A(a().value())) {
// ...
}
}
void ok2() {
// extra variable is not used
// if for some reason we are sure that we have a value
// and we skip checks
auto&& b = a();
for (auto&& e : b.value()) {
// ...
}
}
// it may be that the best choice is to define
A aForced() {
return A(a().value());
}
std::copy_of
as one from the @yakk's answer, at least it would be a good way to make people pay attention to the problem. – Amygdaloid