I have a function defined like this:
void doSomethingWithCustomer (const Customer &customer);
One of my fellow developers called it like this:
Customer *customer = order.getCustomer();
doSomethingWithCustomer (*customer);
Unfortunately, the getCustomer method can return a nullptr, if the order is not tied to a customer.
If getCustomer returns a nullptr, then the application does not crash at the time of the call to doSomethingWithCustomer but rather within the function, where the customer reference is used.
Of course the correct way to write this is to check for customer not being a nullptr first, then call the function if we have a valid customer.
Normally we expect that if a function/method has a reference argument, that the caller checks the validity of it (which wasn’t the case here), instead of the function itself checking the argument.
I know that Visual Studio 2010 (and earlier versions) passes references by actually passing the pointer, but I wonder if this is indicated somewhere in the C++ standard. Can we assume that a reference is always passed as a pointer (personally, I wouldn’t rely on this, but it’s interesting to know it)?
Is it possible to tell Visual Studio that when passing a reference, it should automatically dereference it first and crash at the time of the call rather then somewhere much deeper (doing this in a debug version might be sufficient)?
No, it is not.
The standard does not mandate that the reference should be implemented in terms of pointer.
How to actually implement a reference is an implementation detail which the standard leaves out for implementations to decide on. It only describes the expected behavior from an Reference and one of them is a reference can never be
NULLin a standard conformant program.If your function parameter is expected to be
NULLsometimes then you should pass it as an pointer.