5 ms·
> References in C++ are non-nullable so the precedent already existed. Wrong analogy. References in C++ are not first-class entities. Conceptually, they're _al
by zvrba 8y ago
> References in C++ are non-nullable so the precedent already existed.
Wrong analogy. References in C++ are not first-class entities. Conceptually, they're _alias names_ for existing objects. Unlike C# and Java "references", you cannot "reset" a C++ reference to "point" to another object. Because it's not a pointer. It does not "point". It's an alias. `void f(int& ref)` in C++ is the same as `void f(ref int x)` in C# (the equivalent doesn't exist in java). Inside `f`, you cannot change `x` to "point to some other int" because it's not a pointer!
C# and Java "references" are semantically the same as C++ pointers minus arithmetic.
- AstralStorm 8y agoYes, C++ can have nonnullable smart pointers just fine if that is what you want. They will lose reset call, throw on assigning null T*, static assert on nullptr_t, require full initialization on construction, have maximum exception safety. This could've been done since 2003 but wasn't. There are attempts to bring it into language as part of C++ Core Guidelines project. This is possible because unlike Java and C# not everything can be null.
- jcelerier 8y ago> C# and Java "references" are semantically the same as C++ pointers minus arithmetic. But you can entirely write a shitton of C++ programs that won't use pointers at all - not even shared / unique. In contrast, you can't avoid C# and Java references.
- vbezhenar 8y agoCan you show an example of linked list data structure without pointers?
- jcelerier 8y agoIn more than ten years of programming in C++ I never had once to implement a linked list. That's 100% irrelevant to programming practice. The only reason to implement one is whether it's for academic purposes, else just use `std::{s,}list`.
- lmm 8y agoMy C++ is rusty but you'd do it exactly like you do in ML. Something like: template<typename T> class List<T> { protected: List(); template<typename U> class Visitor<U> { public: U visitNil(); U visitCons(T current, U accumulator); } public: virtual <U> U visit(Vistor<U> visitor); } template<typename T> class Nil<T> extends List<T> { U visit(Visitor<U> visitor) = visitor.visitNil(); } template<typename T> class Cons<T> extends List<T> { private: T head; List<T> &tail; public: Cons(T head, List<T> &tail) { this.head = head; this.tail = tail; } U visit(Visitor<U> visitor) = visitor.visitCons(head, tail.visit(visitor)); }
- vbezhenar 8y agoThanks, that neat. But how would you build a list of arbitrary length and free it later? You'll use pointers, one way or another. The only way to avoid pointers I could imagine is to use stack with recursion, but that's completely crazy and limited programming style.