There is no such thing as "address references". There are "references", and they are different from pointers. C++ references are a very powerful language feature absent from many other languages (e.g. C or Java).
A reference is best pictured as a different name for an existing object. Or better yet, as the object itself. A reference is the object.
That's not at all like a pointer. A pointer is itself an object which happens to point to something else (or to nothing).
They do it for performance reasons.
No, they don't. If they said this, then it doesn't make sense. You don't use references for performance (at least not non-const references), you use them for correctness.
int& foo(int &i)
{
if (i > 10)
{
// or return nullptr;
return NULL;
}
return i;
}
There is no such thing as "null references". Remember, a reference is the object. So what your foo
function here returns is actually the object itself. Not a pointer to it, not its address, but the object itself.
And what object would NULL
or nullptr
be? It doesn't make sense. There cannot be an object which is nothing.
If you need to be able to have a special "nothing" state in your business logic, then you can use something like boost::optional
. Or perhaps you really want a pointer, after all. It depends.
rather than pointer references.
Pointer references exist, but they are not related to your example.
Here is a pointer reference:
int main()
{
int x = 0;
int* ptr = &x;
int*& y = ptr; // "y" is now a different name for "ptr"
}