簡體   English   中英

constexpr與匿名名稱空間

[英]constexpr versus anonymous namespace

創建const值時,以下兩種模式有什么區別?

constexpr int some_val = 0;

VS

namespace {
   const int some_val = 0;
}

我已經習慣了第二種方法,但是第一種等效嗎?

未命名的命名空間充當變量的static :鏈接。

namespace {
   const int some_val = 0;
}

等效於:

static const int some_val = 0;

constexpr不會改變這一點: 演示

現在我們可以比較constconstexpr

  • constexpr變量是在編譯時已知的不可變值(因此可以在常量表達式中使用)
  • const變量是不可變的值,可以在運行時進行初始化。

所以你可能有

int get_int() {
    int res = 0; 
    std::cin >> res;
    return res;
}

const int value = get_int();

但不是

constexpr int value = get_int(); // Invalid, `get_int` is not and cannot be constexpr

最后,某些const值將被視為constexpr因為它將用於:

const int some_val = 0; // equivalent to constexpr int some_val = 0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM