static_assert和assert

assert运行时断言

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

//使用NDEBUG来禁用assert宏
#define NDEBUG
//禁用后程序将继续执行,不会提示错误或崩溃
#ifdef NDEBUG
#define assert(expr) (static_cast<void> (0))
#else

#endif

char* ArrayAlloc(int n){
    //运行时进行断言
    assert(n>2);
    return new char[n];
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    char* tempa = ArrayAlloc(1);
    return a.exec();
}

static_assert静态断言

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

//c11之前可以实现的静态断言方式,通过除0
#define asset_static(e)\
    do{\
    enum{asset_static__=1/(e)};\
    }while(0)

template<typename T,typename U>int bit_copy(T& t1,U& u1){
    //静态断言-c11,表达式的结果为常量,写在函数体外是较好的选择
    //如果程序需要进行运行时检测,还是使用assert宏
    static_assert(sizeof(u1) == sizeof(t1),"t1 and u1 must have same width.");
    memcpy(&t1,&u1,sizeof(u1));
}
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    int tempa1 = 0x2468;
    double b;
    bit_copy(tempa1,b);

    return a.exec();
}

enum FeatureSupports{
    C99=0x0001,
    ExtInt=0x0002,
    SAssert=0x0004,
    NoExcept=0x0008,
    SMAX=0x0010,
};
struct Compiler{
    const char* name;
    int spp;//使用FeatureSupports枚举
};

    //检查枚举值是否完备
    assert((SMAX-1)==(C99|ExtInt|SAssert|NoExcept));
    Compiler tempa={"c1",(C99|SAssert)};
    if(tempa.spp&C99){
        qDebug() << "spp&C99";
    }

猜你喜欢

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