Reputation: 11904
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.
Upvotes: 0
Views: 1458
Reputation: 206577
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.
Upvotes: 2
Reputation: 476990
*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.
Upvotes: 0