Re: References vs Pointers

"Jon Earle" <[email protected]>
Newsgroups gmane.user-groups.linux.ottawa.general
Message-ID <[email protected]>

Stephen M. Webb wrote:
> On 02/07/08 17:07, Jon Earle wrote:
>>
>> Now, I was under the impression that references were just a fancy word for
>> pointers, ie: a reference is an address of an object.  So, why can I not
>> assign the reference to a pointer variable?  Missing something, not sure
>> what.
>
> In C++, a reference is not just a fancy word for a pointer.  It's an entirely
> different beast with entirely different semantics.
>
> If you want to assign an rvalue (like the X parameter in your setval
> function)
> to the address pointer to by a pointer, you need to apply the "dereference"
> operator to obtain the desired lvalue.  Perhaps that's the source of your
> confusion?
>
> void setval(myclass obj, int& x)
> {
>   *obj.i = x;
> }
>
> Or, alternatively, depending on what semantics you desire,
>
> void setval(myclass obj, int& x)
> {
>   obj.i = &x;
> }
>
> In the first example, the value of "j" will be assigned to wherever mc.i
> points (in your code, this will invoke undefined behaviour and unleash
> starved lions on certain parts of PEI, or maybe crash).  In the second
> example, mc.i will contain the address of j.

So, the reference, as received by a function, looks and acts like a parameter
that was passed by value, but actually refers, or points to, the original
value?  In which case, I would need to treat it as if it were not a pointer
but a local parameter and apply the address-of operator to get the original
memory location?

(Lions in PEI... new movie idea, perhaps?  Lazy coder's sloppy code unleashes
some horrible chain of events upon an unsuspecting population?)

-- 
OCLUG general discussion list
[email protected]
http://oclug.on.ca/mailman/listinfo/oclug
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.