简体   繁体   中英

constexpr versus anonymous namespace

What is the difference between the following 2 patterns in creating const values?

constexpr int some_val = 0;

vs

namespace {
   const int some_val = 0;
}

I'm used to the 2nd method but is the 1st equivalent?

unnamed namespace acts as static : linkage of the variable.

namespace {
   const int some_val = 0;
}

is equivalent to:

static const int some_val = 0;

constexpr doesn't change that: Demo

Now we can compare const vs constexpr :

  • constexpr variable are immutable values known at compile time (and so can be used in constant expression)
  • const variable are immutable values which might be initialized at runtime.

so you might have

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

const int value = get_int();

but not

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

Finally some const values are considered as constexpr as it would be for:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM