我是cpp的新手,正在尝试几件事。我似乎无法自行解决这个问题。
#include <cstdio>
#include <stdexcept>
template <class E, class V>
struct Pair {
E first;
V second;
Pair(E fst, V snd) : first(fst), second(snd) {}
E getFirst() { return first; }
V getSecond() { return second; }
};
template <class t, unsigned dim>
struct vec {
t d[dim];
static constexpr int dimen = dim;
t &operator[](unsigned n) {
std::printf("dim: %d %d\n", dim, n);
if (n >= dim) {
std::printf("checking %d\n", n);
throw std::out_of_range("vector index is out of range");
}
return d[n];
};
};
int main() {
try {
Pair<int, vec<int, 2> *> test2(2, new vec<int, 2>{1, 2});
std::printf("%d\n", test2.getSecond()->dimen);
std::printf("before\n");
std::printf("%d\n", test2.getSecond()->d[2]); // it seems like the compiler kind of ignores this
} catch (std::out_of_range e) {
std::printf("Caught!!");
}
return 0;
}
现在,理想情况下,std::printf("%d\n", test2.getSecond()->d[2]);
行应该抛出out_of_range错误,但不是。我的短毛绒实际上警告我这也超出范围。我可以编译并运行该程序,它返回一些垃圾0
值。我的问题是:为什么不引发错误或未捕捉错误?我认为不会引发错误,因为运行时未打印检查。
最佳答案
因为throw
代码实际上从未到达过。
在此行中:
std::printf("%d\n", test2.getSecond()->d[2]);
getSection()
返回指向vec
对象的指针。然后,当您执行->d
时,您将访问d
对象中的vec
数组。因此,当您将[2]
添加到末尾时,您正在访问数组索引2处的元素,而没有调用operator[]
对象的vec
。如果您这样重写:
std::printf("%d\n", (*test2.getSecond())[2]);
然后将在operator[]
对象而不是其数组上调用vec
。请注意,您必须取消引用getSecond()
的结果。或者,您可以更详细:std::printf("%d\n", test2.getSecond()->operator[](2));
工作示例:https://godbolt.org/z/YWKzPz
关于c++ - 为什么我的out_of_range异常没有被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63103535/