I’d like to understand the rationale here better. It seems much better to pass out parameters as reference (Widget&), as it avoids having to check for nullptr. As of C++11, I was taught that raw pointers are now code smell in all but very rare cases, and you usually want to pass out parameters by reference (or, rarely, by smart ptr).
Which is nice, but the real problem always are invalid references/pointers. Which you can't check with a simple ` == nullptr`. So, if an error occurred the reference could be in any state instead of a `0`, which can easily be checked.
The way I look at it is that something has to own the pointer. That ownership should be expressed via std::unique_ptr. If ownership must be shared (which is relatively rare) or you need weak pointers (even more rare), then use std::shared_ptr.
It's not a code smell to receive a pointer parameter because the function or method doesn't own the pointer. I would generally pass const references as parameters except for those cases where you may want to allow a nullptr parameter.
You don't have to check for nullptr. It's the caller's job to adhere to the function contract. A function's caller can screw up in a thousand different ways: why check at runtime for one of those ways?
> by smart ptr
Unnecessary heap allocation (which is what you get with a scheme that forces passing of out parameters via smart pointer) is a bad thing.
Maybe the visibility at the callsite, to make it clear what the parameter is used for because you have to take a pointer to it, and since input parameters can only be passed by value or const reference the only reason to hand out a pointer is an out parameter?
A reference is just a pointer in disguise, and so can still be null if created from a pointer.
The rationale behind passing by ptr is at the call site you have to use the & operator, which makes it immediately obvious to the reader that it's possible the argument is being mutated (because it's not passed by value).
In general it's even better to avoid out parameters entirely, although there are cases where you want to reuse a containers memory where it's a useful technique.
True, but I've seen people exploit undefined behavior to make a null reference. Please don't ask me to explain it, someone might think they understand it and try it.
I’d like to understand the rationale here better. It seems much better to pass out parameters as reference (Widget&), as it avoids having to check for nullptr. As of C++11, I was taught that raw pointers are now code smell in all but very rare cases, and you usually want to pass out parameters by reference (or, rarely, by smart ptr).