C++11新特性-引入關鍵字constexpr

常量表達式(const expression)

常量表達式指在編譯階段就能獲得值的一種表達式,表達式的值是不可改變的。express

const int max_files = 20;             //yes
const int limit = max_files + 1;     //yes
int staff_size = 27;                  //no
const int sz = get_size();            //no

constexpr關鍵字

C++11引入了新關鍵字constexpr,constexpr聲明的變量是const的,且必須用常量表達式來初始化。因此,constexpr聲明的對象必須是全局對象(不在任何函數體內)函數

constexpr int mf = 20;            //20 is a constant expression
constexpr int limit = mf + 1;     //mf+1 is a constant expression
constexpr int sz = size();        //ok only if size is a constexpr function

用constexpr來聲明指針

若是用constexpr來聲明指針的話,constexpr做用於指針自己,而不是指針指向的對象。參考個人博文:C++ 指針
spa

const int *p = nullptr;        //p is a pointer to a const int
constexpr int *q = nullptr;    //q is a const point to int

int i = 5;
int k = 7;
constexpr int j = 42;

int main()
{
    constexpr int *p1 = &i;    //p1是const指針,而不是指向const對象的指針
    *p1 = 6;
    cout << *p1 <<endl;     //output 6
    cout << i <<endl;       //output 6
    
    constexpr const int *p = &i;    //p是指向const對象的的const指針
    *p = 10; //error,指向const對象
    p = &k;  //error,const指針,不能指向新對象
}
相關文章
相關標籤/搜索