std::addressof 作为 C++17 中的常量表达式

std::addressof as a constant expression in C++17

std::addressof 的规范针对 C++17 进行了更改:现在允许它是常量表达式。但是,cppreference 表示:

The expression std::addressof(E) is a constant subexpression, if E is an lvalue constant subexpression.

这是解释here

Introduce the following new definition to the existing list in 17.3 [definitions]: [Drafting note: If LWG 2234 is accepted before this issue, the accepted wording for the new definition should be used instead — end drafting note]

**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]).

所以"constant subexpression"大致就是"you can use it in a constant expression".

What is an example where std::addressof(E) will be a constant expression?

我相信它的目的是在 &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

What is an example where std::addressof(E) will NOT be a constant expression?

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

}