Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There is something about pointers. Pointers are special. But there isn't, and they aren't. They are types (or values) just like any others. In C++, you can say either auto p{...}; or auto* p{...}; and I always use the former in order to make code as much "abstract" as possible.


Every abstraction has a cost. If it is not delivering more value than that cost, it is a net liability. Saying "auto p = " when you could say "auto* p = " saves you practically nothing, but costs the reader, potentially, a lot. Somebody reading the code who doesn't instantly understand without a bunch of poking around that p has reference semantics is at a marked disadvantage. You have stolen that advantage from that reader.

There is a reason that the language permits "auto& r = " and "auto* p = ". That reason is, specifically, to help prevent errors. Failing to spend a single keystroke to help prevent errors is false economy.


Except auto& does not prevent errors, and it is a source of innumerable problems, because '&' is too easy to forget.

auto* does not add anything to making code more reliable, either; it just makes code tied to a particular implementation detail (e.g. I could redefine things using my own pointer-like object, and the * would simply stand in the way for no good reason whatsoever.)


I think ncmncm is a total scrub, but I will say two things:

First, both adding an ampersand after auto when you shouldn't have and not adding it when you should have can lead to logic errors of different kinds. Sometimes either one is fine, sometimes you have to use the correct one.

Second, auto * vs auto by itself has no effect on the generated code, but it can lead to a more robust source. Imagine that you get a pointer from some function and you perform some operations with it, assuming it actually is a pointer in a way that would be invalid if it wasn't. If the function signature later changes to return a pointer-like object, you'd want the compiler to give you an error to know to fix that code. In other words, you should use auto if you really don't care at all if the value is a pointer or not, and you should use auto * if you're assuming it's a pointer.


It has always been permitted to not make your code as clear as it could be, and always will be. Each of us may choose to help the person reading our code, but not all of us care to.




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

Search: