In C++ Primer 5th, it says that
constexpr imposes a top-level const on the objects it defines.
So how I can I declare a pointer with a constexpr specifier imposing a low-level const, i.e. a pointer pointing to a constexpr object?
A constexpr object is an object just like any other. The fact that its value is computed at compile time does not alter this.
Often, the compiler will seek to avoid actually emitting code to create const values and objects if it knows that they will never be needed , for example when objects are static const.
By taking the address of an object, whether constexpr, static const or an auto variable, the compiler is forced to actually create the object.
So:
constexpr int i = 5; // need not be actually created
const int* pi = &i; // but now it must be, because we took its address
constexpr const int* pi2 = &i; // constexpr pointer to const object - we took its address so it must exist
const void emit(int);
int main()
{
emit(i);
emit(*pi);
emit(*pi2);
}
results in:
main:
subq $8, %rsp
movl $5, %edi <-- compiler knows it's a fixed value
call emit(int)
movq pi(%rip), %rax <-- compiler dereferences the pointer
movl (%rax), %edi
call emit(int)
movl $5, %edi <-- compiler knows it's a fixed value
call emit(int)
xorl %eax, %eax
addq $8, %rsp
ret
pi:
.quad i
i:
.long 5
constexpr pointer?constexpr int (for example). The type of that would be const int - it would just happen to be computed at compile time (so you could use it in static asserts and template arguments, for example)
constexpror it's not. Doesn't really make much sense to have something that's partiallyconstexpr.constandconstexprare also orthogonal concepts.constexprimpliesconstbut not the other way around.constexpris tomutableasconstis tovolatile. Doesn't contradict what I said.