Is passing by reference is a special case of passing as pointer?
This question already has an answer here:
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.
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.
链接地址: http://www.djcxy.com/p/20742.html上一篇: 声明一个符合Swift协议的变量或常量
下一篇: 传递引用是传递指针的特例吗?