假设我们有一个返回的函数std::optional<A>
。那么在基于范围的 for 循环中使用结果的正确方法是什么?最简单的方法不起作用:
for (auto&& e : a().value()) {
// ^--- A&& is returned, so A is destructed
// before loop starts
如果我们有T optional::value() &&
而不是,这个问题就不会存在T&& optional::value() &&
,但是 STL 和 Boost 都以第二种方式定义它。
处理这种情况的正确方法是什么?我不喜欢我能想到的两种解决方案(沙箱):
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());
}