4 ms·
> 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 p
by 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/