3 ms·
With const pointers, you have no idea if the parameter is implicitly optional, if it must point to a valid object, if it will throw an error when provided with
by MereInterest 3y ago
With const pointers, you have no idea if the parameter is implicitly optional, if it must point to a valid object, if it will throw an error when provided with a null pointer, if it will segfault when provided with a null pointer. Not even reading the header file will help you here.
With const references you never have this problem.
- alexvitkov 3y agoYes, but non-const references are utter trash since you can't tell you're passing a mutable reference when looking at the call site, so for the non-const I'll always pass by pointer. Const references are less offensive, but I'm not going to pass non-const by pointer and const by reference, that's just inconsistent for no reason. If null is not a valid value, throw an assert at the beginning of the function. It's not like references can't be in a broken state, they're just syntax sugar for pointers (that also happens to wildly complicate the language's type system)
- ninkendo 3y ago> Const references are less offensive, but I'm not going to pass non-const by pointer and const by reference, that's just inconsistent for no reason. Why use pointers at all? Just use const references for immutable stuff, regular references when you want mutation, normal values when you want copy semantics, and smart pointers for other cases (unique_ptr for move semantics, shared_ptr for lack of clear ownership, etc.) If you want to represent nullability, std::optional is a good choice. > If null is not a valid value, throw an assert at the beginning of the function Yikes. This means the compiler will not catch it for you. Why make this a runtime issue? Use the type system to your advantage.
- alexvitkov 3y agoIf references were guarenteed sane and consistent values like in Rust, sure - but it's trivial to get a bogus reference in C++, so I don't buy the type safety thing. An assert actually catches errors, a reference just declares intent. As for smart pointers there's a lot of domains with tight performance requirements where you can't afford them - and to be quite frank, if you can afford to use shared_ptr you can also afford GC, so just use a sane language
- ninkendo 3y ago> but it's trivial to get a bogus reference in C++ How? Honestly curious. (You can certainly reinterpret_cast something and ignore all warnings, but is that all?)
- showdead 3y agoFrom 2008, but still applicable: https://nealabq.com/blog/2008/09/15/bugs-returned-mem-refs/ https://nealabq.com/blog/2008/09/15/bugs-returned-mem-refs/
- MereInterest 3y agoYeah, I’d beg to differ there. Non-const references have all the non-nullable benefits over pointer-to-non-const as const references have over pointer-to-const. While I’d prefer a call-site syntax difference similar to what Rust has, the non-null ability of references is well worth it.