lsdsjy
lsdsjy

Reputation: 63

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?

Upvotes: 3

Views: 2546

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69864

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

Upvotes: 2

Related Questions