简体   繁体   中英

Does dereference return the object itself or the reference to the object?

Say I have MyObj* ptr; , and is *ptr a reference to some MyObj object, or is itself the object?

If *ptr is the object itself, why is it legal to do the following then?

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.

From the C++11 standard (emphasis mine):

5.3.1 Unary operators [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.

*ptr is an expression . 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". (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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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