How to define a pointer pointing to a constexpr variable?

会有一股神秘感。 提交于 2021-01-27 19:09:34

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37789026/how-to-define-a-pointer-pointing-to-a-constexpr-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!