【问题标题】:std::addressof as a constant expression in C++17std::addressof 作为 C++17 中的常量表达式
【发布时间】:2016-08-02 09:22:00
【问题描述】:

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

表达式std::addressof(E) 是一个常量子表达式,如果E 是 一个左值常量子表达式。

  • 什么是常量子表达式?
  • std::addressof(E) 将成为常量表达式的示例是什么?
  • std::addressof(E) 不是常量表达式的示例是什么?

【问题讨论】:

    标签: c++ memory constexpr c++17 addressof


    【解决方案1】:

    这是解释here

    在 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 执行时给出一个常量表达式(假设 & 调用内置的 address-of 运算符)。

    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
    
    }
    

    【讨论】:

    • so x 是一个常量表达式,但不是常量子表达式,在第二个例子中?一清二楚
    • @M.M 其实x在第二个例子中也是一个常量表达式……我可能应该选择一个更好的例子。
    • 我说不是常量sub表达式
    • @M.M 哦,等等,让我重新开始。 x 如果应用了左值到右值的转换,则它是一个常量表达式,但它不能是一个作为左值的常量表达式,因为它引用了一个自动存储持续时间的对象。不过,x 肯定是一个常量子表达式,无论是作为泛左值还是纯右值。我应该添加一个新示例。
    • @M.M 我改变了这个例子,希望现在更清楚了。
    猜你喜欢
    • 1970-01-01
    • 2019-08-22
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多