为什么不使用S :: x?

编程入门 行业动态 更新时间:2024-10-25 20:23:59
本文介绍了为什么不使用S :: x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

从 cppreference 中考虑此示例:

struct S { static const int x = 1; }; void f() { &S::x; } // discarded-value expression does not odr-use S::x

我同意&S::x是一个舍弃值表达式,因为该标准指出(9.2,第 n4700 )

表达语句具有以下形式

expression-statement: expression_opt ;

该表达式是一个废弃值表达式(第8条)...

但是,足以让S::x不被 odr-使用吗? 6.2,第3段[basic.def.odr]声明

变量x的名称显示为可能评估的表达式ex,除非

使用 odr

  • ...
  • 如果x是对象,则 ex是表达式e 的潜在结果集中的元素,其中
    • 将左值到右值转换(7.1)应用于e或
    • e是一个舍弃值表达式(第8条).

问题是舍弃值表达式&S::x没有潜在结果(这意味着S::x不是&S::x的潜在结果),如您从6.2第2段中所见[basic.def .odr]:

...表达式e的潜在结果集定义如下:

  • 如果e是id表达式(8.1.4),则该集合仅包含e.
  • 如果e是具有数组操作数的下标操作(8.2.1),则该集合包含该操作数的可能结果.
  • ...
  • 否则,该集合为空.

然后,您如何解释S::x不是未使用?

解决方案

它确实是使用过的.您的分析是正确的(我已经修正了前一阵子)

Consider this example from cppreference:

struct S { static const int x = 1; }; void f() { &S::x; } // discarded-value expression does not odr-use S::x

I agree that &S::x is a discarded-value expression, since the standard says (9.2, paragraph 1 [stmt.expr] from n4700)

Expression statements have the form

expression-statement: expression_opt ;

The expression is a discarded-value expression (Clause 8)...

However, is that enough for S::x to not be odr-used? 6.2, paragraph 3 [basic.def.odr] states

A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless

  • ...
  • if x is an object, ex is an element of the set of potential results of an expression e, where either
    • the lvalue-to-rvalue conversion (7.1) is applied to e, or
    • e is a discarded-value expression (Clause 8).

The problem is that the discarded-value expression &S::x has no potential results (which means that S::x is not a potential result of &S::x), as you can see from 6.2, paragraph 2 [basic.def.odr]:

... The set of potential results of an expression e is defined as follows:

  • If e is an id-expression (8.1.4), the set contains only e.
  • If e is a subscripting operation (8.2.1) with an array operand, the set contains the potential results of that operand.
  • ...
  • Otherwise, the set is empty.

Then, how can you explain that S::x is not odr-used?

解决方案

It is indeed odr-used. Your analysis is correct (and I fixed that example a while ago).

更多推荐

为什么不使用S :: x?

本文发布于:2023-11-25 03:09:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628076.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!