简体   繁体   English

取消引用返回对象本身还是对象的引用?

[英]Does dereference return the object itself or the reference to the object?

Say I have MyObj* ptr;假设我有MyObj* ptr; , and is *ptr a reference to some MyObj object, or is itself the object? ,并且*ptr是对某个MyObj对象的引用,还是它本身就是对象?

If *ptr is the object itself, why is it legal to do the following then?如果*ptr是对象本身,那么为什么执行以下操作是合法的?

MyObj* someFunc(){
  MyObj* p;
  ...
  return p;
}

MyObj someOtherMyObjInstance;
*someFunc() = someOtherMyObjInstance. 

If ptr points to a valid object, then the evaluation of the expression *ptr results in an lvalue reference to the object.如果ptr指向一个有效的对象,则表达式*ptr计算结果会产生对该对象的左值引用。

From the C++11 standard (emphasis mine):从 C++11 标准(强调我的):

5.3.1 Unary operators [expr.unary.op] 5.3.1 一元运算符[expr.unary.op]

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. 1 一元 * 运算符执行间接操作应用它的表达式应是指向对象类型的指针或指向函数类型的指针,结果是引用表达式指向的对象或函数的左值

*ptr is an expression . *ptr是一个表达式 This expression has a value, and that value has a type.这个表达式有一个值,这个值有一个类型。 If ptr is dereferenceable, then the value of the evaluated expression is the object that ptr points to, and its type is MyObj , and its value category is "lvalue".如果ptr是可解引用的,则计算表达式的值是ptr指向的对象,其类型为MyObj ,其值类别为“lvalue”。 (This means, for example, that this value can bind to an lvalue reference, and that you can take its address.) If on the other hand ptr is not dereferenceable, then evaluating the expression results in undefined behaviour. (这意味着,例如,这个值可以绑定到一个左值引用,并且你可以获取它的地址。)另一方面,如果ptr引用,那么评估表达式会导致未定义的行为。

The assignment at the end of your code is simply an assignment to the object that is the value of the dereferencing expression.代码末尾的赋值只是对作为解引用表达式值的对象的赋值。

Note that an expression can never be a reference, since the type of a value is always an object type, and never a reference type.请注意,表达式永远不能是引用,因为值的类型始终是对象类型,而不是引用类型。 Reference types are useful to bind to values, but they are not themselves values.引用类型对于绑定到值很有用,但它们本身不是值。 The value of evaluating a reference is the object that's being referred to.评估引用的值是被引用的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM