Agrudge Amicus
Agrudge Amicus

Reputation: 1103

Clarification regarding need for fixed address in context of constexpr pointers and references

In Primer (while studying constexpr) I found that:

variables defined inside a function ordinarily are not stored at a fixed address. Hence, we cannot use a constexpr pointer to point to such variables

  1. Is it valid for all the values calculated at compile time or is it just a constraint for using keyword constexpr?
  2. Does const keyword not ensures that the object would be determined (evaluated its value) at compile time despite being initialised by a literal?
  3. Why define some reference with constexpr keyword:

          int i=9;   //Declared as global variable
          constexpr int &ref=i;
    

since constexpr implies top-level constness which means the ref would be constant (which was true even when constexpr wasn't used as we can't refer to any other variable) and it fails to deliver the something which const reference does?

Upvotes: 0

Views: 53

Answers (1)

MSalters
MSalters

Reputation: 179927

You seem to have a few misconceptions.

constexpr values are pretty much the only ones that behave like compile-time constants. So in q1 you're making a distinction that does not exist. You can store any address in a regular const pointer i.e. T* const .

Q2 is pretty much the same misconception. You can store a user's input in a const std:: string. That only means you can't change the string later.

Q3 is just a case of the language not trying to ban unnecessary things. There are a million other redundant things you can do.

Upvotes: 1

Related Questions