gpt4 book ai didi

c++ - 为什么我的out_of_range异常没有被捕获

转载 作者:行者123 更新时间:2023-12-02 09:48:13 26 4
gpt4 key购买 nike

我是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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com