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

标签 c++ templates error-handling

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

相关文章:

java - 为什么 ClassNotFoundException 会表现出这种行为?

c++ - 初始化私有(private)静态变量

由于 Cmake 检查,Android NDK 项目需要数年时间才能完成 gradle buid

c++ - 在Python中解析.c/.cpp/.py源文件以获取包含的函数列表

c++ - CRTP - 如何从派生类调用方法的基类实现?

c++ - std::function 返回任何可求和类型?

java - 处理 ANTLR4 中的错误

c++ - 如何规避 Intel C++ 编译器的 `decltype` 和继承问题?

c++ - 使用模板模板参数和 enable_if 获得正确的重载选择

powershell - Powershell中Try/Catch的错误处理问题