gpt4 book ai didi

c++ - 获取文字的地址,而不是 `constexpr`

转载 作者:太空狗 更新时间:2023-10-29 20:21:04 25 4
gpt4 key购买 nike

严格按照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++ - 获取文字的地址,而不是 `constexpr`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46208655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com