15 ms·
Const all the things?
- tored 5y agoTL;DR Don’t overuse const. Agree. - Hur lyckades du refaktorisera om den variabeln? - Äh, det var väl ingen const!
- kwhitefoot 5y agoDet var kult!
- oreally 5y agoThe const infection is real in a codebase, and it's the very definition of a bureaucratic practice that saps the fun out of coding. Hopefully people use locality of variables more.
- kbob 5y agoI wouldn't choose C++ if I wanted to have fun. Practically any language (maybe not XML) is more fun to get things done in. If using C++ is the right business decision, I'll use it, but I won't expect to enjoy it.
- p2t2p 5y agoSame in Java. People final the hell out of _local_ variables.
- thfuran 5y agoBefore the concept of effective finality had compiler support, it was often necessary.
- lelanthran 5y agoI feel like I should bookmark this page, to use as a reply to every person who says "Why use C when C++ is available?" The cognitive overhead of figuring out when "bits are moved implicitly" vs "bits are copied implicitly" vs "bits are used after free" can be quite high in a mature codebase. After all, all those problems above disappear when using C.
- ryandrake 5y ago> Pass out-parameters by pointer: Widget*. I’d like to understand the rationale here better. It seems much better to pass out parameters as reference (Widget&), as it avoids having to check for nullptr. As of C++11, I was taught that raw pointers are now code smell in all but very rare cases, and you usually want to pass out parameters by reference (or, rarely, by smart ptr).
- ReleaseCandidat 5y ago> as it avoids having to check for nullptr Which is nice, but the real problem always are invalid references/pointers. Which you can't check with a simple ` == nullptr`. So, if an error occurred the reference could be in any state instead of a `0`, which can easily be checked.
- nly 5y agoA reference is just a pointer in disguise, and so can still be null if created from a pointer. The rationale behind passing by ptr is at the call site you have to use the & operator, which makes it immediately obvious to the reader that it's possible the argument is being mutated (because it's not passed by value). In general it's even better to avoid out parameters entirely, although there are cases where you want to reuse a containers memory where it's a useful technique.
- dataflow 5y ago> A reference is just a pointer in disguise, and so can still be null if created from a pointer. References cannot be null legally.
- bluGill 5y agoTrue, but I've seen people exploit undefined behavior to make a null reference. Please don't ask me to explain it, someone might think they understand it and try it.
- masklinn 5y ago> A reference is just a pointer in disguise, and so can still be null if created from a pointer. That’s an immediate UB right there.
- unwind 5y agoI don't have a lot of opinions about C++ (which is good, since the number of cases covered here was quite large). For C, I really do think that const-ing all the things when possible helps, since doing so should (I don't have evidence, I'm not a CS researcher) help protect against accidental modification which can lead to dangerous bugs. More, I really think it makes the programmer's intent much more clear, which I find important especially in large and perhaps not so disciplined codebases as the article author seems to assume. Basically, in a language where all variables are modifiable by default, not consting (to me) means "I'm going to be modifying this later, watch out!". Also for code still using C89-ish style of declaring all variables at the beginning of the scope. If you have a 150-line function with 13 lines of variables at the top, it would really make it easier to know which variables to focus on understanding if some are const and some not. I also think it just makes the code more self-explanatory and "confident"-looking when things, even local variables that are only referenced a couple of times in the next few lines, are const. Something like: // Make the string one character shorter. void truncate(char *s) { if (s != NULL) { const size_t len = strlen(s); if (len > 0) { s[len - 1] = '\0'; } } } This is ultra-trivial, but to me it reads much better when the 'len' is const. Sure I can see that there is only two further references to that variable, but it's just ... simpler. You could write it in a more "elite" old-sk00l C style like this: // Make the string one character shorter. void truncate(char *s) { if (s != NULL) { size_t len = strlen(s); if (len-- > 0) { s[len] = '\0'; } } } But to me that is just needless complexity. I did not Godbolt the above to see if there's any difference in the generated code, but would naively expect there not to be. Addendum/edit: I'm still really opposed (like the article) to const:ing scalar function arguments, since I feel that leaks internal information (whether or not the code inside a function is going to change the value of an argument) to the outside which is bad. I would probably treat the value of an argument as const anyway though, it's just simpler.
- LevelAd8 5y ago2 more instructions in GodBolt for the second version, in the end the urge to look cool and "elite" more often than not causes trouble. Unless there really is a need for complexity, it's almost always better to follow KISS principle
- ukoki 5y ago> The above code is bad because it makes unnecessary copies. plus doesn’t need its own copies of s and t; it can get by with just references to its caller’s strings. I was under the impression the compiler was smart enough to 'move' rather than 'copy' a value if it can prove it's not reused. And also to infer a 'const' reference if it can prove the reference is not modified.
- nly 5y agoThe compiler isn't allowed to move instead of copy if the code implies a copy. What it can do however is completely elide the copy, and not call the copy constructor. Const isn't really useful to the optimiser in any way, roughly all it does really is effect the overload resolution rules, and how the compiler maps statically initialized data in to your final binary.
- account42 5y ago> Const isn't really useful to the optimiser in any way, roughly all it does really is effect the overload resolution rules, and how the compiler maps statically initialized data in to your final binary. const on pointers and references is not useful at all, but const on variables is useful as it means the value is never allowed to change. For example: const int x = 0; do_something(&x); return x; // Optimizer can assume that x == 0 here even if it knows nothing about do_something See: https://godbolt.org/z/4T8M3eK1x https://godbolt.org/z/4T8M3eK1x
- jcelerier 5y ago> Pass out-parameters by pointer: Widget*. OP says this like this is an industry rule of sorts but I've pretty much always seen non-const references for this. Using pointers is terrible because now you have to add a check for null inside your function, as its API contract says "I can accept null values", while references make it clear that it does not make sense to call if you don't have a correct object to pass it. > That’s right: the point of making a class with private members is to preserve invariants among those members. How would OP make a class, which loads content on construction which must absolutely not being changed after construction then, even within its implementation ? "Being careful" is really not sufficient in my experience, and introducing child classes just to enforce the invariant that "const" provides is actively harmful to readability.
- lelanthran 5y ago> OP says this like this is an industry rule of sorts but I've pretty much always seen non-const references for this. Using pointers is terrible because now you have to add a check for null inside your function, as its API contract says "I can accept null values", while references make it clear that it does not make sense to call if you don't have a correct object to pass it. The other side of the coin is that it hurts readability if you are passing non-const references. When a function takes a non-const reference, the caller looks like this: foo (bar); // Have to read the header to know if bar is modified. When a function takes a pointer, the caller looks like this: foo (&bar); // Immediately clear that we cannot gloss over this line in code-review. Since I read code much more than I write it, it's easier for me to determine that local non-const variables that are used as arguments to a function are not getting modified. A better (but not best) solution might be to have the language recognise and enforce nullability on arguments. Still not perfect (pointer may be non-null but invalid), but better. One other benefit pointer parameters have over reference parameters is that the API contract is more flexible. For example, I have a function that accepts a network connection, mynet_accept(int listener_fd, char **remote_ip, uint16_t *remote_port); Having the caller specify NULL for `remote_ip` means that the callee just ignores the parameter. Same for `remote_port`. If that was changed to use references, the caller will have to declare variables just to satisfy the parameter list, even if they never intend to use them.
- m12k 5y agoI wonder what C++ would feel like if instead of making it a burden to add const everywhere, you made it a burden to remove it? E.g. everything was const unless you added a keyword (e.g. mut).
- Kranar 5y agoYou'd get a language that is wildly incompatible with C and hence you may as well use a different language.
- dataflow 5y agoUnfortunately there are a lot of overly-strong claims in this blog post; the choices are not as clear-cut as the author makes them seem. I'll list a few examples to illustrate (these are not exhaustive): > What we mean to write is: auto plus(const std::string& s, const std::string& t) { return s + t; } To a first-order approximation, sure. But arguably it's better to pass 's' by value and 't' by const reference, then do s += t and return s. That lets you reuse any existing buffer if you receive an rvalue, and lets the caller preallocate the buffer if it so desires. This can help you avoid a heap allocation. > This function is wrong: auto plus(const std::string s, const std::string& t). The programmer meant to type const std::string& s. Not necessarily. The const tells the programmer that s will never be modified. That's an excellent constraint that can make a nontrivial function easy to reason about. (Obviously that doesn't imply you should do this everywhere. I'm just pointing out it's not "wrong".) P.S. I hear optimizers can sometimes optimize const objects, though I don't have proof handy for that example, so someone else can fact-check that part. > or maybe they meant const std::shared_ptr<Connection>& for efficiency (but in that case why aren’t they simply passing const Connection& from the caller?) That "why" actually has an answer: "because the function might only copy the shared_ptr conditionally, and desire to remain efficient in the no-copy case". > Const data members are never a good idea. This one is correct!
- nemetroid 5y ago> That "why" actually has an answer: "because the function might only copy the shared_ptr conditionally, and desire to remain efficient in the no-copy case". Yeah. This blog post has a few well argued guidelines about passing smart pointers to functions, which covers this case: https://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ https://herbsutter.com/2013/06/05/gotw-91-solution-smart-poi... > Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership; otherwise use widget* instead (or if not nullable, a widget&).
- tsimionescu 5y ago> Obviously that doesn't imply you should do this everywhere. I'm just pointing out it's not "wrong". The article makes a point about contracts. In their code base, it's always wrong, since function parameters, by convention, are only allowed to be (a) non-const values, (b) const references, or (c) non-const pointers. Anything else, in their codebase indicates an error. Their point is that these three are all you need, so that getting in the habit of only using them helps maintenance, since during code review or something you know for sure that any other parameters is a mistake someone made, not an intentional choice (because of the coding standard). > P.S. I hear optimizers can sometimes optimize const objects, though I don't have proof handy for that example, so someone else can fact-check that part. That can happen, if a reference to your local variable is passed to a function. For example, tried this in Godbolt [0] void some_func(const int& x); void some_other_func(int x); int bar() { int x = 123; some_func(x); volatile int y = x; } The final line directly writes 123 to y if x is const (or if calling some_other_func()), but it reads again from memory as it is. This happens because some_func could do this: void some_func(const int& x) { const_cast<int&>(x) = 7; } If x was `const int x`, this is UB, but if x is `int x`, the program MUST write 7 to y. Note however that this optimization only happens (with clang) IF the value of x is a compile-time constant. If instead the value is only known at runtime, there is 0 difference - the value of x is still read from the stack, not kept in a register for example. [0] https://godbolt.org/z/YKf4ndq1v https://godbolt.org/z/YKf4ndq1v
- nemetroid 5y agoThe case against local variables basically boils down to: 1. "I don't need the compiler to avoid writing bugs" > I don’t need a keyword just to tell me that a variable isn’t modified during its lifetime. I can see that fact at a glance [...] Not terribly convincing. 2. might inhibit automatic move of return value This is an edge case that does not affect correctness, only performance, and rarely pops up unless the code has other, worse problems. (also, when it does happen, it is trivially found by static analysis tools, and clang-tidy will point it out to you) > But suppose there were many more lines of code interspersed between the [definition of fullName] and the final call to e->setName(fullName). That call makes an unnecessary copy. The programmer might try to fix it by writing e->setName(std::move(fullName))… but guess what? fullName was const-qualified, so the move does nothing! If there are "many more lines of code interspersed between the variable definitions and the final call", this implies that fullName is used somewhere between its definition and the final call (it makes no sense to declare fullName before it is required). But after fullName is moved from, it should not be referenced again. This means that rearranging the function (so that fullName is used after the move) would introduce a correctness bug. This is in itself a bad situation which should be avoided by refactoring, so it's not a great example (it's also not great that the actual example is not written out as code, merely handwaved). But this is actually an example where defaulting to const could be at least a bit helpful, because doing so makes all non-const variables stand out and warrant extra attention.
- gpderetta 5y agoFor the most part I agree with the article, but yes, for long functions I will often const locals that I want to make sure they stay constant (i.e. there is some cross variable invariant that I want to make sure always hold). I won't bother for functions of less of 10 lines (but it is not a rule and I wouldn't want it to be enforced). I also see no issues in consting members of classes that don't have value semantics.
- thamer 5y ago> I don’t need a keyword just to tell me that a variable isn’t modified during its lifetime. I agree that this isn't very well argued, and variable re-use is a common source of bugs – especially variables that are used several times in a single function for different purposes. On a similar point, Java has `final` instead of `const` and it does apply to local variables, including to guarantee that a variable is not only not modified, but set exactly once. Something like this: final String foo; if (condition) { foo = someValue(); } else { foo = otherValue(); } Omitting any of the assignments leads to a compilation error. It works with complex if conditions with multiple branches, and even with `switch`. If a branch throws an exception, that's also acceptable as the variable is guaranteed not to be used below. I find it pretty useful; doesn't C++ provide a similar construct?
- ajuc 5y agoIt is a sign of great design of a programming language when people tell you "there's dozens ways to pass parameters but all except these 3 are always wrong".
- asddubs 5y agoi mean it's C++, there's like 4 ways to initialize variables that are all subtly different.
- wscott 5y agoA little more than that: http://randomcat.org/cpp_initialization/initialization.png http://randomcat.org/cpp_initialization/initialization.png
- phorkyas82 5y agoThis is truly terrifying.
- masklinn 5y agoInterestingly that’s a pretty rust-ic view of things: Rust parameters can be passed either by value (`T`), by reference (`&T`) or by mutable reference (`&mut T`). This differs slightly from TFA because a difference is made (at callsite) between by-val and by-ref, but since Rust uses destructive moves that makes a lot of sense. As TFA recommends, rust data members can’t be made readonly, that’s just not part of their properties. Diverging from TFA, local bindings are immutable (by default), however there have been rumblings about dropping this, and essentially always making them mutable because the signal is pretty low. While it’s possible to make parameters mutable e.g. pub fn foo(mut self) AFAIK that is not exposed in any way to the caller, as far as Rust is concerned, a move (pass-by-value) is a move, whoever the owner is can do whatever they want e.g. this is entirely valid: pub fn foo(self) { let mut self = self; And the previous is just a shortcut for that.
- cesarb 5y ago> Diverging from TFA, local bindings are immutable (by default), however there have been rumblings about dropping this, and essentially always making them mutable because the signal is pretty low. I hope that never happens; one of the best things in Rust is that it's easier (less typing) to make things non-mutable, which in the case of local bindings tends to encourage a more functional programming style (for instance, it encourages "let x = if foo { bar } else { baz };" instead of "let mut x; if foo { x = bar; } else { x = baz; }").
- creata 5y agoAgreed, but for that particular example, the compiler is smart enough to see that x is assigned exactly once, so you can have x be immutable in both examples. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=504978eb7a3de80c22d00fd402816660 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- chrismorgan 5y ago> there have been rumblings about dropping this Really? I don’t pay attention to everything that goes on, but keep an ear to the general pulse, and I haven’t heard anything even vaguely serious about this since the mutpocalypse back in ¿2014?, which failed (sadly, in my opinion—though I was undecided back then). But I wouldn’t mind dropping immutable local bindings; as you say, it’s low signal and mostly just an annoyance. I’m interested if you have any citation, however loose; I’m curious. —⁂— I think the interesting difference between Rust and C/C++ in this space is the spelling, and just how significant its impact is. There are two parts to this: ① The reading order. C/C++ reading order is a hodge-podge of right to left and left to right. And what’s the difference between `T const * name` and `T * const name`? There’s a fair chance one who doesn’t know and hasn’t developed the appropriate intuition will guess incorrectly. (In pseudo-Rust terms: they’re `mut name: const T` and `const name: mut T`, and I think I got that the right way around.) See the worked example in https://en.wikipedia.org/wiki/Const_(computer_programming)#C++_convention https://en.wikipedia.org/wiki/Const_(computer_programming)#C... for a particularly painful example: `double (*const (fun(int))(double))[10]`. I believe that’s equivalent to `fun: fn(int) -> mut fn(double) -> const mut [double; 10]` in Rust (keeping raw pointers and C++ type names), which is much clearer, reading purely left to right. ② The default for constness. C/C++ default to mutable and require that you spell out any qualifiers (const in one directions, restrict in the opposite, dunno if there are others). Rust goes with a more sound hierarchical model instead, defaulting to immutable (the more restrictive) and requiring that you spell out any functional additions you want (mutability, which actually corresponds more to restrict), and I’m glossing over references versus raw pointers but because of having taken a different foundational design it’s all more sound and sensible to my eyes, with the simplest spelling providing the least privilege, and more keywords adding more privilege. (Raw pointers are spelled const/mut rather than just /mut as with &/&mut, but that’s to avoid confusion or error, given their role in FFI.) It’s an important philosophical difference; C++ templates versus Rust generics exhibit much the same difference. Well, is it any wonder that Rust has kept on surfacing LLVM bugs because noalias wasn’t exercised much in C/C++ code? When you have to add a restrict keyword, especially when the compiler doesn’t help you… Well, the glib summary is that Rust is better in this area, with a better theoretical foundation and lessons learned from the likes of C/C++, but of course it’s more nuanced, and there are some types of architectures that don’t translate well to Rust. But it’s interesting to reflect on the differences. Because Rust basically does const all the things, and makes it easier and safer to do so. Kinda funny that I started the second half of this comment saying the spelling had a particularly significant impact, and ended up back at the memory/pointer/reference model differences. That’s definitely critical, but the spelling is a major part of it too.
- wscott 5y agoOk HN I am proud of you. I read the article and had a sinking feeling that the top comment would be: "Well actually... you should really be using string_view instead of..." Perhaps that is true but that would be intentionally missing the point of his arguments.
- fancyfredbot 5y agoToday I learned that using const prevents the compiler from using move semantics. I am sad that I didn't already know this and also annoyed that C++ is so fiddly. This is less obscure than the thread about std::launder on HN a few days ago but still counts as obscure for me, and you don't even get a friendly compiler warning when you do this. It just underlines for me the amount of knowledge required to truly become an expert on C++. It's such a powerful language but I sometimes wonder if all this complexity is a necessary consequence of that power.
- gpderetta 5y agoI would say this is pretty obvious. Moving form an object will leave it in a different state than it was before. Obviously it can't be done for const objects.
- Kranar 5y agoIt's not obvious at all, the issue is that move semantics in C++ don't really have much to do with the concept of moving. Most languages that have move semantics treat moves as a kind of relocation of a value from one place to another, hence the name. You're not changing the value, you're relocating it and in fact once the relocation is complete the original location is destroyed. So for example in Rust, you are absolutely welcome to move an immutable object. In C++, a move is an awkward kind of mutable copy operation with a special overloading rule that allows binding to rvalue references. There is nothing obvious about how it works, people get tripped up by it all the time along with all the additional complexity about when moves happen vs. when an elision happens vs. when a copy happens, the fact that T&& means wildly different things depending on whether T is a template parameter, and the bloated set of value categories introduced by it: glvalues, xvalues, rvalues, prvalues. I absolutely sympathize with anyone who doesn't feel like knowing all these C++isms.
- gpderetta 5y agoMost languages? I only know of two languages with move semantics: C++ and Rust. The latter has the benefit of a clean slate and build upon C++ experience. C++ had to be backward compatible with pre C++11 and couldn't make destructive moves work.
- einpoklum 5y agoMost of the author's points are well-taken. But not all of them... for example: auto plus(std::string s, std::string t) { return s + t; } > The above code is bad because it makes unnecessary copies Maybe, maybe not. A compiler may inline it (although, TBH, even regardless of parameter constness, std::string is very copy-prone in general.) > What we mean to write is: auto plus(const std::string& s, const std::string& t) Not quite. That is, this implies we don't want to take rvalues (e.g. temporary strings). It will work with rvalues, but we might be making copies for them. When you think about it, we don't even need the actual string class; we only need access to the characters. So... auto plus( std::string_view s, std::string_view t) (this is C++17; before that, try: https://github.com/martinmoene/string-view-lite https://github.com/martinmoene/string-view-lite ) Also, why use the `auto` return type? I avoid it unless it hides some complex monstrosity, or it's a template where it's difficult to figure out. Here I would write: std::string plus( std::string_view s, std::string_view t) > In function signatures: the ugly is the bad This is... a good principle, in thoery, but in practice, not always :-) But this principle is part of why we don't want to talk about const &'s and just pass things by value if we can.
- junon 5y agoAuthor makes no mention of copy ellision. Huh.
- floor_ 5y agoI feel like every programmer should take a step back and see if const spamming actually helps them. I never have problems writing to memory I shouldn't but it could just be my programming style. So if you know you don't have them problem you can just stop guarding against it. You have a limited amount if life to spend on projects after all.
- xg15 5y ago> Data members: Never const > What good is a value-semantic Employee class if you can’t assign or swap values of that type? Question from a Java guy: Is immutability not a thing in C(++) land? Seems to me most modern high-level languages strive to make structs with "value" semantics immutable, i.e. members are set once on creation and then never changed. You're supposed to interact with those structs through pointers, so most usecases for copying or overwriting a struct don't apply. I get that this doesn't translate fully well to C's programming model where you seem to interact a lot more with the actual data structures (and not just pointers). But wouldn't the ability to restrict arbitrary changes to a struct still be important?
- clappski 5y ago> But wouldn't the ability to restrict arbitrary changes to a struct still be important? Typically immutability in C++ is at the interface scope rather than structural, e.g. prefer this struct MyType { int x_; MyType( int x ) : x_( x ) {} }; void do_the_thing( const MyType& mt ); // mt.x_ = 1; doesn't compile, mt is const over this struct MyType { const int x_; MyType( int x ) : x_( x ) {} }; void do_the_thing( MyType mt ); // mt.x_ = 1; doesn't compile, x_ is const
- gpderetta 5y agoIn c++ you normally interact with value types by copying them around. Same way you would do for an int for example. Immutability is enforced with a top level const.
- irrational 5y agoIn JS I prefer let over const because it is fewer characters to type.
- ariedro 5y agoFewer than var or let?
- irrational 5y agoWhat? I said I prefer let.
- WalterBright 5y ago> “Please give me references to two of your strings, and by the way, I might modify them.” Since C++ const is not transitive, one can still modify what the const reference indirectly refers to.
- lkjjfowjflasdf 5y agohttps://digitalmars.com/d/archives/digitalmars/D/Transitive_const_sucks_58111.html https://digitalmars.com/d/archives/digitalmars/D/Transitive_...
- ramesh31 5y agoApplies to JavaScript as well. There's almost no legitimate reason to use `let` anywhere.
- lkjjfowjflasdf 5y ago> Do pass expensive types by const reference. Consider `foo(T t)` where `foo` takes ownership of `T` and allows move semantics, but there is risk of copy if `t` is not an r-value reference.
- Kranar 5y agoIt's very rare where doing that is a good idea. A constructor is about the only time when you get much of a benefit.
- klyrs 5y agoFunny. I felt attacked by the intro, as I am a very big fan of locking things down with const and getting yelled at by the compiler for attempting to modify a const. But, the article goes on to attack stupid shit that I'd never do with const. (Though, I do think that there's marginal value in non-movable classes with public const data members: you don't need to implement a getter) We're left with three good uses: 1. returning const references to private data 2. passing const references as arguments 3. const class methods Ho-hum. I came expecting a fight, not validation.
- beders 5y agoI do admire all the different ways you can shoot yourself in the foot with using C++. The relentless pursue of 'what would the compiler do and does it costs us cycles?' is a great mindset to have - if you can afford it. Thanks for the interesting analysis of const.
- dataangel 5y agoThe problem is C++ has the wrong default. You should have to opt-in to mutability. Rust gets this right.
- thomassmith65 5y agoI don't code much in C++, but I have to imagine the verbosity of its 'const' syntax is the real problem. Syntax aside, if a variable is not actually variable, it's arguably a lie to declare it as something other than constant. In languages with better 'const' syntax, it's not just a matter of performance, it's a legibility issue.