C++> static_assert靜態斷言與assert動態斷言

static_assert

static_assert靜態斷言,是C++關鍵字,做用是讓編譯器在編譯期對常量表達時進行斷言。若是經過,就不報錯;若是不經過,就報錯。
用法:c++

```c++
static_assert(常量表達式, 錯誤提示信息);ide

常量表達式的值爲true或者false,或者能夠轉化爲true/false。
若是斷言不經過,程序編譯也不會經過。

### assert
assert動態斷言,從C繼承過來的宏定義,頭文件assert.h。
從下面源碼能夠看到,assert是把表達式經過static_cast<bool>轉換成bool類型,從而實現斷言。

```C++
// # if defined __cplusplus

#  define assert(expr)                          \
     (static_cast <bool> (expr)                     \
      ? void (0)                            \
      : __assert_fail (#expr, __FILE__, __LINE__, __ASSERT_FUNCTION))

assert無論斷言是否經過,都不會影響編譯。性能

static_cast與assert主要區別

1. 斷言通關是否影響編譯
static_cast: 斷言不經過編譯出錯,由於是編譯器在編譯器進行檢查;
assert: 斷言不經過不會影響編譯,程序運行時檢查;調試

```C++
static const int a = 0;
static_assert(a > 1, "error1"); // 沒法經過編譯
static_assert(a > -1, "error2"); // 能夠經過編譯code

assert(0); // 能夠經過編譯, 但沒法繼續運行
assert(1); // 能夠經過編譯, 能夠繼續運行繼承

***2. 是否影響程序運行效率 ***
static_assert: 所包含的代碼不會生成目標代碼,不會影響程序性能;
assert: 會影響程序性能,經常使用於調試階段,正式釋放軟件時一般關閉assert功能;
參考[c++靜態斷言(static_assert)](https://zhuanlan.zhihu.com/p/79743589)
相關文章
相關標籤/搜索