i'm trying to come up with a concrete reasoning why to use a pointer over a reference as a return type from a function ,
my reasoning is that if inadvertently a null value is returned to a reference type it could not be checked , and could lead to run-time errors
int& something(int j)
{
int* p = 0 ;
return *p;
}
void main()
{
int& i = something(5);
i = 7; // run-time error
}
if i had used a pointer i could check it and avoid the error the pointer return value would act as a contract to that a value must be returned.
void main()
{
int* i = something(5);
if( i != null )
*i = 7;
}
any thoughts would be appreciated again ,
what would you use and why reference or pointer
thanks in advance.
References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.
Return Function Pointer From Function: To return a function pointer from a function, the return type of function should be a pointer to another function. But the compiler doesn't accept such a return type for a function, so we need to define a type that represents that particular function pointer.
References are usually preferred over pointers whenever you don't need “reseating”. This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.
References are not a kind of pointer. They are a new name for an existing object.
You could use a pointer instead of a reference if:
Regardless, you would not want to return either a pointer or a reference to a local variable.
References are a different way of thinking. Think of references as "pointers to existing objects". Once you do that, you'll understand why they can't be NULL - the object exists and the reference points to it.
Therefore, if your function returns a reference to something that it creates, it needs to guarantee that it actually does create a valid object. If it does not, or is unable to, then that is grounds to throw an exception.
Contrast that with a pointer. A pointer can be NULL and the caller will have to deal with a NULL return value. Therefore, if your function cannot guarantee that it will return a valid reference and you don't want to throw exceptions, you will need to use pointers.
If you inadvertently return a null value, that's a bug. You can just as easily place the check inside something()
and throw an exception if it's null.
Having said that, the historical convention is to return heap objects via pointers, even if they are guaranteed to be non-null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With