其他分享
首页 > 其他分享> > c – 取字面的地址,而不是’constexpr`

c – 取字面的地址,而不是’constexpr`

作者:互联网

严格按照C 14的规则,至少由cppreference.com给出的规则,不是第(1)行是一个常数表达式吗?

constexpr const int* addr(const int& ir) { return &ir; }
constexpr const int* tp = addr(5); // (1)

确实,这不是地址常量表达式,因为& ir不是静态对象的地址(& ir是此上下文中临时的地址,在编译时无法知道).

但它是一个核心常量表达式,因为它不违反任何后面列出的核心常量表达式规则,它没有关于获取对象地址的后续规则.

解决方法:

不,addr(5)不是常量表达式,因此发布的代码格式不正确.是的,你是正确的addr(5)是一个核心常量表达式.

我可以看到为什么你可以单独从cppreference页面思考核心常量表达式,整数常量表达式,转换常量表达式,文字常量表达式,引用常量表达式和地址常量表达式都是常量表达式的类型.但真正的定义在C 14 [expr.const] / 4中给出:

A constant expression is either a glvalue core constant expression whose value refers to an object with static storage duration or to a function, or a prvalue core constant expression whose value is an object where, for that object and its subobjects:

  • each non-static data member of reference type refers to an object with static storage duration or to a function, and

  • if the object or subobject is of pointer type, it contains the address of an object with static storage duration the address past the end of such an object, the address of a function, or a null pointer value.

作为“核心常数表达”并没有多少直接影响;它只是一个术语,用于帮助定义“整数常量表达式”,“T型转换常量表达式”和“常量表达式”.并且“常量表达式”实际上描述了“核心常量表达式”描述的表达式的子集,而不是超集.

例如,要完成,使示例格式错误的段落([dcl.constexpr] / 9)需要一个常量表达式,而不是核心常量表达式,作为初始化程序.

A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. If it is initialized by a constructor call, that call shall be a constant expression. Otherwise, or if a constexpr specifier is used in a reference declaration, every full-expression that appears in its initializer shall be a constant expression. [Note: Each implicit conversion used in converting the initializer expressions and each constructor call used for the initialization is part of such a full-expression. – end note]

标签:c,c14,constexpr,memory-address
来源: https://codeday.me/bug/20190823/1699080.html