Re: basic question about references

From: Ben Cottrell (bench_at_bench333.screaming.net)
Date: 01/09/05


Date: Sun, 09 Jan 2005 16:17:13 +0000

zapro wrote:

>>The NumSequence1 constructor accepts objects of the type
>>std::vector<int> - it does not accept addresses.
>
>
> I see. This is one misunderstanding I had. Basically, if I have a
> variable declared as a reference, I am going to use that variable just like it
> was the object the reference was initialized with.

Effectively, yes.

>>Furthermore, by declaring NumSequence1(std::vector<int> &re) you have
>>specified that "re" is a Reference to an object, so "re" is not an
>>object itself.
>>
>>you could think of a reference in this context like an alias or nickname
>>- You will be referring to an existing object somewhere else in the
>>program, but doing so under the name "re".
>>
>
>
> So, if I understand correctly, using the "nickname" you refer to the
> object directly: changes you do on the reference will be done on the
> object.

Correct

> This is also done with a correctly initialized pointer, anyway.

Yes, although you have to dereference the pointer in order to refer to
the object.

> The
> difference seems to be that with a pointer, you just have an address that
> "may" point to some object or be null; with a reference you are sure
> it's not null and it will point to the same object it was initialized with.
> Are there any other differences?

This is nearly right, Unfortunately, as with Pointers, you can't
guarantee with references that an object will always be there.

Since a few lines of code can speak 1000 words, take this example as an
illustration.

void foo(MyClass& mc)
{
     mc.MyValue = 0;
}

int main()
{
     MyClass* pMyClass = NULL;
    // Oops, I forgot to allocate pMyClass.
     foo( *pMyClass );
    // Passing a value of the type MyClass to "foo"
    // However, no object was created
}

"foo" accepts the value because it is of the type "MyClass", although no
checks are done to see that an object exists behind the value. When
"foo" attempts to perform an operation on the reference "mc", the
program crashes, since "mc" is referring to nothing.

This is of course, a buggy, non-standard bit of code. However, it
demonstrates using dynamic memory allocation, that you cannot guarantee
the existence of an object.

-- 
Ben Cottrell AKA Bench