Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a pointer pointing to a constexpr variable?

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?

like image 306
lsdsjy Avatar asked Mar 07 '26 11:03

lsdsjy


1 Answers

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
like image 112
Richard Hodges Avatar answered Mar 09 '26 00:03

Richard Hodges



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!