Frage

I haven't understand passing by reference in C++ completely. I already read related questions like the following ones.

But even though I understand that it is different to a pointer, I don't fully understand the concept of reference in C++. How does it work? I seems like reference is a special case of a pointer and might be implemented as such by the compiler. But it behaves different on programming level. Is that correct?

Is the concept of passing by reference a special case of passing a pointer to that value? Many times I have to decide whether to use reference or pointer while programming. Moreover I want to understand the underlying principle. Is only the memory address copied?

War es hilfreich?

Lösung 2

yes, it's essentially the same as a pointer but a nicer and safer version as the pointer address cant be changed or set to null. i see it mainly as a means to have nice function interfaces without requiring the user of the interface to worry about pointers - ie function remain simple yet the object is not copied, purely its address. class copy constructor is a prime example of where references are crucial.

Andere Tipps

A reference is a pointer with some special restrictions. A reference must never be un-initialized. When a reference is created it must point to something. This is useful when wanting a "pointer" that will not be NULL.

Furthermore a reference cannot have the address it holds changed, therefor it is a constant pointer.

It has some nice syntactic sugar to allow it to use the dot operator, making it useful when changing from by-value code to by-reference code.

In practice using a reference in a function as a parameter or return value usually would signify "by address, cannot be NULL and must be a valid object". Using a pointer instead would usually signify "could be NULL, so NULL must be handle". By pointer also allows for pointer arithmetic and manipulation.

What you should use is really what you're most comfortable with, assuming you understand both. I myself prefer pointers.

Edit: As pointed out in the comments here, you cannot take the address of a reference directly, as it will return the address of what the reference is referring to. This is yet another restriction that does not apply to an average pointer.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top