posted:
I get that these two are different
int* get()
{
static int m;
return &m;
}
int& get()
{
static int m;
return m;
}
int& get()
{
static int m;
int* p=&m;
return p; // should it be *p or p?
}
but can there be a case when pointers may be confused with references?
The reason I am asking is because the pointer contains the address of
an object so its value is a reference.
Don't think of "p" as a value. Think of it as an expression, which, when
evaluated, can yield a value. "p", as an expression, has a type.
In your last function above, look at the types. Firstly, we have:
static int m;
int* p = &m;
"m" is an expression of the type, "int". Therefore, "&m" is an expression
of the type "int*". (Don't be thinking about values yet). "p" on the left
hand side is also of the type "int*", so everything is fine and dandy
with our assignment statement. The types match, so now we can evaluate
"&m" and store the value in "p".
Your function's return type is "int&". Therefore, when you make the
"return" statement, the type of the expression after the "return" keyword
must be "int", and, not only that, it must be an "l-value" so that you
can bind a reference to it. (It also must be non-const in this case.).
The following won't work:
return 5;
because, while the type requirements have been satisfied, the "l-value"
and "const" requirements haven't.
As I said, "p" is an expression of the type "int*". We want this function
to return a reference to an object of the type "int". We turn an "int*"
into an "int" by using the asterisk operator like as follows: *p.
Therefore, the "return" statement should be:
return *p;
The moral of the story is, that I find that I can understand these things
if I think in terms of expressions rather than values. Think of "p" as an
expression of type "int*"; therefore if we put an asterisk before it
like:
*p
then we have an expression of type "int". If we put an ampersand before
it:
&p
then we have an expression of type "int**" (not taking into account the
constness).
If you get your head around the following line of code I'm about to
write, you'll have a firm understanding of how it all works:
int& = *new int;
-Tomás
-Tomás