3 ms·
Serenity C++ patterns: References instead of Pointers
- spacechild1 4y agoI think (or really hope) this is covered in every C++ beginner's course. Fun fact: the original motivation for adding references was because they are needed for operator overloading.
- colejohnson66 4y agoReferences, at least in C++, are a horrible idea. Without an IDE, I have no way of knowing if a function can overwrite my local variable. For example, does this modify ‘x’? some_func(x); Who knows! Gotta find the definition and figure out which overload the compiler chose! At least with pointers, I can see: some_func(&x); If there was a keyword that the caller must use, it would fix this: some_func(ref x); <rant> C# does that and manages just fine with operator overloading. Each operator function is static and returns a new value rather than modifying “this”. </rant>
- spacechild1 4y ago> References, at least in C++, are a horrible idea. Without an IDE, I have no way of knowing if a function can overwrite my local variable. Total hyperbole. If you don't use an IDE or an editor with plugins, that's your problem. Also, I don't see how pointers and references are any different in this regard. Both can be const or non-const. Your 'ref' keyword would't achieve anything.
- spacechild1 4y ago> C# does that and manages just fine with operator overloading. Each operator function is static and returns a new value rather than modifying “this”. C++ does as well with certain operators, such as operator+. These are commonly implemented as free functions. But certain operators, such as operator= or operator+=, are supposed to mutate the object. In this case you simply can't return a new object.
- spacechild1 4y agoFinally, (r-value) references are the basis for move semantics in modern C++.