【发布时间】:2015-04-19 12:50:43
【问题描述】:
考虑这段代码:
try {
const Asdf &a = map1.at(index1);
const Bsdf &b = map2.at(index2);
} catch(std::out_of_range&) {
return false;
}
// <code>
std::cout<<a[b[42]]; // May throw std::out_of_range which should not be caught here.
return true;
<code> 使用 a 和 b。我有两个选择:
- 将
<code>放入try 块中 - 在 try 块中获取指针,然后取消引用它们
第一个选项是错误的,因为如果 <code> 抛出 std::out_of_range 函数将返回 false,这只会在地图查找失败时发生。
第二个选项可能有点丑:
const Asdf *a;
const Bsdf *b;
try {
a = &map1.at(index1); // What?
b = &map2.at(index2);
} catch(std::out_of_range&) {
return false;
}
std::cout << (*a)[(*b)[42]];
return true;
有没有更好的方法? Python 中的 try-except-else 之类的东西会很好,但在 C++ 中不存在。
【问题讨论】:
-
如果
<code>抛出std::out_of_range那么你应该抓住它,有什么问题? -
@maroun-maroun 我不想从
<code>抓到std::out_of_range -
然后用内部
try子句包围它。 -
不确定它是否比指针更好,但是
std::reference_wrapper<const Foo> -
@johannes-schaub-litb
std::reference_wrapper<Foo>不会从Foo继承operator[]。这使得它比第二个选项更糟糕。