2016-06-13 86 views
1

在C++中的引物5,它說,如何定義一個指向constexpr變量的指針?

constexpr強加它定義了對象的頂層常量。

那麼,如何可以我宣佈一個constexpr符強加一個低級別的常量,即一個指針指向一個constexpr對象的指針?

+1

至少據我記得這句話只是意味着constexpr也意味着在常量變量。所以它需要一個const指針?你試過什麼了?爲什麼你首先需要一個指向它的指針?或者你只是想知道如何? –

+0

整個表達式都是'constexpr'或不是。具有*部分*'constexpr'的東西真的沒什麼意義。 'const'和'constexpr'也是正交的概念。 'constexpr'暗示'const',但不是相反。 –

+0

@sleeptightpupper ...直到C++ 14之後,它具有可變的constexpr對象是完全合法的 –

回答

1

一個constexpr對象就像任何其他對象一樣。其值在編譯時計算的事實不會改變這一點。

通常,編譯器會努力避免實際發出代碼來創建const值和對象,如果它知道它們永遠不會被需要,例如對象爲static const

通過取對象的地址,無論是constexpr,static 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 $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 
+0

那麼,直截了當的描述。但我仍然無法弄清楚爲什麼沒有這種方法來定義低級別的'constexpr'指針? – lsdsjy

+0

constexpr不是類型簽名的一部分。這更像是對代碼生成器的一個指令(當然,它不止這些)。所以指向一個constexpr對象的想法是沒有意義的,因爲不存在像'constexpr int'類型的對象(例如)。它的類型是'const int' - 它恰好在編譯時計算(例如,你可以在靜態斷言和模板參數中使用它) –

+0

優秀的解釋。非常感謝! – lsdsjy