noexcept修饰符与noexcept操作符

#include<cassert>
#include<cstring>
#include<iostream>
using namespace std;

void Throw(){
    throw 1;
}
void NoBlockThrow(){
    Throw();
}
//表示函数不会抛出异常,如果抛出回调用std::terminate中断程序执行
//noexcept为修饰符
void BlockThrow()noexcept{
    Throw();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    try{
        Throw();
    }
    catch(...){
        qDebug() << "Found Throw.\n";
    }

    try{
        NoBlockThrow();
    }
    catch(...){
        qDebug() << "Throw is no block.\n";
    }

    try{
        BlockThrow();
    }
    catch(...){
        cout << "Found Throw 1.\n";
    }

    return a.exec();
}

template<class T>
//由T()表达式是否会抛出异常决定fun()是否会抛出异常
//noexcept(T())中noexcept为操作符
void fun()noexcept(noexcept(T())){

}

//C++11中析构函数默认为noexcept(True),
//当显示制定为noexcept(false),
//或类的基类或成员有noexcept(false)的析构函数,析构函数不再保持默认值
#include<cassert>
#include<cstring>
#include<iostream>
using namespace std;

struct A{
    ~A(){
        throw 1;
    }
};
struct B{
    ~B()noexcept(false){
        throw 2;
    }
};
struct C{
    B b;
};
int funA(){A a;}
int funB(){B b;}
int funC(){C c;}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    try{
        funB();
    }
    catch(...){
        qDebug() << "caught funB.\n";
    }

    try{
        funC();
    }
    catch(...){
        qDebug() << "caught funC.\n";
    }

    try{
        funA();
    }
    catch(...){
        qDebug() << "caught funC.\n";
    }

    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/yuxing55555/article/details/80855274