QList的at当超出范围时,不抛出异常,而是程序直接崩溃。是因为QList的at函数如下
template <typename T>
inline const T &QList<T>::at(int i) const
{ Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::at", "index out of range");
 return reinterpret_cast<Node *>(p.at(i))->t(); }

Q_ASSERT_X is useful for testing pre- and post-conditions during development. It does nothing ifQT_NO_DEBUG was defined during compilation.

和c语言的assert有些像,有些人使用习惯了c#的list,喜欢抛出异常的版本,抱怨c++的版本。其实写一个抛出异常的泛型list并不是费劲的事情。如下,利用子类的函数名和父类函数名相同时,会覆盖父类函数(除非显示调用父类)的特性,感谢c++的using声明和可变模板参数(variadic templates)。可推广到其他泛型类。当调用at函数时,不再只是assert,而是会抛出异常。

#include <QCoreApplication>
#include <QException>
#include <QList>
#include <QDebug>
class MyException :public QException
{
public:

};
template<typename ...Args>
class ExceptionList :public QList<Args...>
{
public:
    using BaseType=QList<Args...>;
    using BaseType::QList;
    const_reference at(int index)const{
        if (length() <= index)
            throw MyException();
        return BaseType::at(index);
    }
};


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    try{
        ExceptionList<int> f_list={1,2,3,7};
        f_list.at(4);
    }
    catch(MyException&){
        qDebug()<<"catch the exception";
    }
    return a.exec();
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐