簡體   English   中英

std :: addressof作為C ++中的常量表達式17

[英]std::addressof as a constant expression in C++17

為C ++ 17改變了std::addressof的規范:現在允許它是一個常量表達式。 但是, cppreference說:

如果E是左值常量子表達式,則表達式std::addressof(E)是常量子表達式。

  • 什么是常量子表達式?
  • 什么是std::addressof(E)將是常量表達式的示例?
  • 什么是std::addressof(E)不是常量表達式的例子?

在這里解釋。

在17.3 [定義]中對現有清單中引入以下新定義:[起草說明:如果在本期之前接受LWG 2234,則應使用新定義的接受措辭 - 最終起草說明]

 **constant subexpression** [defns.const.subexpr] an expression whose evaluation as a subexpression of a *conditional-expression* *CE* (5.16 [expr.cond]) would not prevent *CE* from being a core constant expression (5.20 [expr.const]). 

因此,“常量子表達式”大致意味着“您可以在常量表達式中使用它”。

什么是std :: addressof(E)將是常量表達式的示例?

我相信它的目的是在&E做的時候給出一個常量表達式(假設&調用內置的地址運算符)。

constexpr int x  = 42; // static storage duration
constexpr int* p1 = &x; // x is an lvalue constant subexpression
constexpr int* p2 = std::addressof(x); // x is an lvalue constant subexpression

什么是std :: addressof(E)不是常量表達式的例子?

std::map<int, int> m;
void f() {
    int& r = m[42];
    constexpr int* z1 = &r; // error: r is not a constant subexpression
    constexpr int* z2 = std::addressof(r); // likewise

    constexpr int x = 43; // automatic storage duration
    constexpr const int y1 = *&x;                // ok; x is a constant subexpression
    constexpr const int y2 = *std::addressof(x); // likewise
    constexpr const int* p1 = &x;                // error: p1 points to an automatic object
    constexpr const int* p2 = std::addressof(x); // likewise

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM