Qt 抛出异常的容器

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();
}


  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值