Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Serenity C++ patterns: References instead of Pointers (awesomekling.github.io)
12 points by klaussilveira on May 13, 2022 | hide | past | favorite | 5 comments


I 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.


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. 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>


> 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.


> 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.


Finally, (r-value) references are the basis for move semantics in modern C++.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: