gpt4 book ai didi

c++ - 多个左值等价定义

转载 作者:行者123 更新时间:2023-11-30 01:05:47 24 4
gpt4 key购买 nike

Microsoft 左值定义:

An lvalue refers to an object that persists beyond a single expression.

A second定义:

The expression E belongs to the lvalue category if and only if E refers to an entity that ALREADY has had an identity (address, name or alias) that makes it accessible outside of E.

我写了下面的代码:

class A{};

const A& f1()
{
return A();
}

const int& f2()
{
return 1;
}

int main() {
cout<<&f1()<<endl; // this prints everytime "0".
cout<<&f2()<<endl; // this prints everytime "0".
return 0;
}
  1. 为什么 f1()f2()lvalue 表达式?
  2. 为什么 lvalue referencervalue 的地址为零?
  3. 为什么这两个定义是等价的?

最佳答案

  1. Why f1() and f2() are lvalue expressions?

因为每个都是对返回左值引用的函数的函数调用。

标准草案:[expr.call]

11 A function call is an lvalue if the result type is an lvalue reference type or ...


Why the & character after the type name makes it an lvalue reference?

标准草案:[dcl.ref]

1 In a declaration T D where D has either of the forms

& attribute-specifier-seqopt D1
&& attribute-specifier-seqopt D1

and the type of the identifier in the declaration T D1 is “derived-declarator-type-list T”, then the type of the identifier of D is “derived-declarator-type-list reference to T” ...

2 A reference type that is declared using & is called an lvalue reference ...


  1. Why an addres of lvalue reference to rvalue is zero?

行为未定义。

标准草案:[expr.unary.op]

3 The result of the unary & operator is ... the result has type “pointer to T” and is a prvalue that is the address of the designated object

没有指定对象,标准也没有定义 addressof 运算符在这种情况下的行为。

标准草案:[defns.undefined]

behavior for which this document imposes no requirements

[ Note: Undefined behavior may be expected when this document omits any explicit definition of behavior ...


  1. Why are both definitions equivalent?

它们不一定等同。其中一个或两个可能不正确。两者似乎都是左值表达式的描述,而不是定义。

规范定义在C++标准文档中。

What is the definition of lvalue by the standard?

标准草案:[basic.lval]

  • (1.1) A glvalue is an expression whose evaluation determines the identity of an object, bit-field, or function.

...

  • (1.3) An xvalue is a glvalue that denotes an object or bit-field whose resources can be reused (usually because it is near the end of its lifetime). [ Example: Certain kinds of expressions involving rvalue references ([dcl.ref]) yield xvalues, such as a call to a function whose return type is an rvalue reference or a cast to an rvalue reference type. — end example  ]

  • (1.4) An lvalue is a glvalue that is not an xvalue.

[expr] section 定义语言中每个可能的表达式,如果表达式是左值,则说明。 “是一个左值”出现了 37 次,但这种简单的搜索不一定是详尽无遗的。

关于c++ - 多个左值等价定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47956757/

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