如何定义指向 constexpr 变量的指针?

How to define a pointer pointing to a constexpr variable?

在 C++ Primer 5th 中,它说

constexpr imposes a top-level const on the objects it defines.

那么我如何声明一个带有 constexpr 说明符的指针并强加一个低级常量,即指向 constexpr[=17= 的指针] 对象?

constexpr 对象与其他对象一样。它的值是在编译时计算的这一事实不会改变这一点。

通常,编译器会设法避免实际发出代码来创建 const 值和对象,如果它知道它们永远不会被需要的话,例如当对象是 static const.

通过获取对象的地址,无论是 constexprstatic const 还是自动变量,编译器都被迫实际创建对象。

所以:

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);
}

结果:

main:
        subq    , %rsp
        movl    , %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    , %edi      <-- compiler knows it's a fixed value
        call    emit(int)

        xorl    %eax, %eax
        addq    , %rsp
        ret
pi:
        .quad   i
i:
        .long   5