21

I am interested in the idea of C++-like const not that particular execution (like casting away const).

Take for example C# -- it lacks C++-like const, and the reason for it is the the usual -- people and time. Here additionally it seems the C# team looked at the C++ execution of const, marketing CLR and had enough at this point (see why there is no const member method in c# and const parameter ; thank you Svick). Be if we move further than that, is anything else?

Is there something deeper? Take for example multi-inheritance -- it is usually seen as hard to grasp (for the user) and thus not added to the language (like diamond problem).

Is there something in NATURE of const that pose a problem that it is better for language to avoid it? Something like deciding if const should be deep or shallow (having const container does it mean I cannot add new element or alter existing elements as well; what if elements are of reference type)?

UPDATE: while I mention C#, and thus making a historical perspective I am interested in the nature of potential problems of const to the language.

This is not a challenge of the languages. Please ignore such factors as current trends or popularity -- I am interested only in technical issues -- thank you.

9
  • 3
    as an aside: multiple inheritance may not be hard to grasp, but method resolution can become quite ugly. Naive depth-first resolution quickly becomes unintuitive (“diamond problem”). The C3 method resolution order (published '96) solves this, but is certainly not easy to understand. Outlawing multiple inheritance can therefore often seem quite sensible – but the real problem is that Java predates the C3 algorithm, and C# oriented itself after Java.
    – amon
    Mar 4, 2014 at 21:30
  • 3
    @amon A lot of people don't really think multiple inheritence is a feature you want to have in the first place, e.g. the creators of the D programming languge: It's a complex feature of debatable value. It's very difficult to implement in an efficient manner, and compilers are prone to many bugs in implementing it. Nearly all the value of MI can be handled with single inheritance coupled with interfaces and aggregation. What's left does not justify the weight of MI implementation. (source)
    – jcora
    Mar 4, 2014 at 22:21
  • 5
    Duplicate of stackoverflow.com/q/4150478/41071.
    – svick
    Mar 4, 2014 at 23:31
  • 2
    Even without Multiple Inheritance, you can already encode any 3-SAT problem as Method Resolution (or more precisely Overload Resolution) in C#, thus making it NP-complete. Mar 5, 2014 at 3:00
  • 1
    @svick, thank you very much. Since I didn't have any answers for this question I took a liberty of heavily editing it, to focus on the nature of the problem, not the historical reasons, because it seems 99% of them was "time+people+anti C++ bias+CLR". Mar 5, 2014 at 6:52

4 Answers 4

12

Note sure if this qualifies for you, but in functional languages like Standard ML everything is immutable by default. Mutation is supported through a generic reference type. So an int variable is immutable, and a ref int variable is a mutable container for ints. Basically, variables are real variables in the mathematical sense (an unknown but fixed value) and refs are "variables" in the imperative programming sense - a memory cell that can be written to and read from. (I like to call them assignables.)

I think the problem with const is two-fold. First, C++ lacks garbage collection, which is necessary to have non-trivial persistent data structures. const must be deep to make any sense, yet having fully immutable values in C++ is impractical.

Second, in C++ you need to opt into const rather than opt out of it. But when you forget to const something and later fix it, you'll end up in the "const poisoning" situation mentioned in @RobY's answer where the const change will cascade throughout the code. If const was the default, you wouldn't find yourself applying const retroactively. Additionally, having to add const everywhere adds a lot of noise to the code.

I suspect the mainstream languages that followed (e.g. Java) were heavily shaped by C and C++'s success and way of thinking. Case in point, even with garbage collection most languages' collection APIs assume mutable data structures. The fact that everything is mutable and immutability is seen as a corner case speaks volumes about the imperative mindset behind popular languages.

EDIT: After reflecting on greenoldman's comment I realized that const isn't directly about the immutability of data; const encodes into the type of the method whether it has side effects on the instance.

It's possible to use mutation to achieve referentially transparent behavior. Suppose you have a function that when called successively returns different values - for example, a function that reads a single character from stdin. We could use cache/memoize the results of this function to produce a referentially transparent stream of values. The stream would be a linked list whose nodes will call the function the first time you try to retrieve their value, but then cache the result. So if stdin constains Hello, world!, the first time you try to retrieve the value of the first node, it'll read one char and return H. Afterwards it'll continue to return H without further calls to read a char. Likewise, the second node would read a char from stdin the first time you try to retrieve its value, this time returning e and caching that result.

The interesting thing here is that you've turned a process that's inherently stateful into an object that's seemingly stateless. However, it was necessary to mutate the object's internal state (by caching the results) to achieve this - the mutation was a benign effect. It's impossible to make our CharStream const even though the stream behaves like an immutable value. Now imagine there's a Stream interface with const methods, and all your functions expect const Streams. Your CharStream can't implement the interface!

(EDIT 2: Apparently there's a C++ keyword called mutable that would allow us to cheat and make CharStream const. However, this loophole destroys const's guarantees - now you really can't be sure something won't mutate through its const methods. I suppose it's not that bad since you must explicitly request the loophole, but you're still completely reliant on the honor system.)

Secondly, suppose you have high-order functions - that is, you can pass functions as arguments to other functions. constness is part of a function's signature, so you wouldn't be able to pass non-const functions as arguments to functions that expect const functions. Blindly enforcing const here would lead to a loss of generality.

Finally, manipulating a const object doesn't guarantee that it's not mutating some external (static or global) state behind your back, so const's guarantees aren't as strong as they initially appear.

It's not clear to me that encoding the presence or absence of side effects into the type system is universally a good thing.

6
  • 1
    +1 thank you. Immutable objects is something else than C++ const (it is more of a view). But say, C++ would have const by default, and var on demand would leave only one problem -- the depth? Mar 5, 2014 at 13:56
  • 1
    @greenoldman Good point. It's been a while since I used C++ so I forgot you can have a const reference to a non-const object. Even so, I don't believe it makes any sense to have a shallow const. The whole point of const is the guarantee that you won't be able to modify the object through that reference. You're not allowed to circumvent const by creating a non-const reference, so why would it be OK to circumvent const by mutating the object's members?
    – Doval
    Mar 5, 2014 at 14:09
  • +1 :-) Very interesting issues in your update (living with non/const lambdas and maybe weaker problem with external state), I have to digest it longer. Anyway, as for your comment I don't have anything evil in mind -- quite contrary, I am looking for features in order to increase clarity of the code (another one: non-null pointers). Same category here (at least it is my purpose) -- I define func foo(const String &s) and this is a signal s won't be changed in foo. Mar 5, 2014 at 16:33
  • 1
    @greenoldman I can definitely see the appeal and rationale. However, I don't think there's a real solution to the problem other than avoiding mutable state as much as possible (along with other nasty things like null and inheritance.)
    – Doval
    Mar 5, 2014 at 17:56
  • "constness is part of a function's signature, so you wouldn't be able to pass non-const functions as arguments to functions that expect const functions." This sentence might need clarification. At least in C++ there are no const functions, as applying the concept of const-ness to functions seems illogical: What would a "mutable" function modify, its own instructions? Maybe you were thinking of const parameters, or so-called const member functions (where the const denotes the const-ness of this)?
    – hoffmale
    Jan 21, 2020 at 16:16
8

The main problem is programmers tend not to use it enough, so when they hit a place where it's required, or a maintainer later wants to fix the const-correctness, there is a huge ripple effect. You can still write perfectly good immutable code without const, your compiler just won't enforce it, and will have a more difficult time optimizing for it. Some people prefer their compiler not help them. I don't understand those people, but there are a lot of them.

In functional languages, pretty much everything is const, and being mutable is the rare exception, if it's allowed at all. This has several advantages, such as easier concurrency and easier reasoning about shared state, but takes some getting used to if you are coming from a language with a mutable culture. In other words, not wanting const is a people issue, not a technical one.

2
  • +1 thank you. While immutable object is something else than I am looking for (you can make object immutable in C# or Java), even with immutable approach you have to decide if it is deep or shallow, take for example the container of pointers/references (can you change the value of objects being point to). After a day it seems the major problem is rather what is set as default, and it is easily solvable when designing new language. Mar 5, 2014 at 14:01
  • 1
    +1 for the lolz @ "Some people prefer their compiler not help them. I don't understand those people, but there are a lot of them." Mar 5, 2014 at 22:18
7

I see the drawbacks as:

  • "const poisoning" is a problem when one declaration of const can force a previous or following declaration to use const, and that can cause its previous of following declarations to use const, etc. And if the const poisoning flows into a class in a library that you don't have control over, then you can get stuck in a bad place.

  • it's not an absolute guarantee. There are usually cases where the const only protects the reference, but is unable to protect the underlying values for one reason or another. Even in C, there are edge cases that const can't get to, which weakens the promise that const provides.

  • in general, the sentiment of the industry seems to be moving away from strong compile-time guarantees, however much comfort they may bring you and I. So for the afternoon I spend touching 66% of my code base because of const poisoning, some Python guy has banged out 10 perfectly workable, well-designed, well-tested, fully functional Python modules. And he wasn't even hacking when he did it.

So maybe the question is, why carry forward a potentially controversial feature that even some experts are ambivalent about when you're trying to gain adoption of your spiffy new language?

EDIT: short answer, a new language has a steep hill to climb for adoption. It's designers really need to think hard about what features it needs to gain adoption. Take Go, for example. Google sort of brutally truncated some of the deepest religious battles by making some Conan-the-Barbarian style design choices, and I actually think the language is better for it, from what I've seen.

17
  • 2
    Your second bullet is not correct. In C++, there are three/four ways to declare a reference/pointer, wrt. constness: int * mutable pointer to mutable value, int const * mutable pointer to const value, int * const const pointer to mutable value, int const * const const pointer to const value.
    – phresnel
    Mar 5, 2014 at 7:38
  • Thank you. I asked about the nature, not the marketing ("industry moving away" is not a nature of C++-like const), thus such "reasons" I consider irrelevant (for this question at least). About const poisoning -- can you give example? Because AFAIK it is the advantage, you pass something const and it should remain const. Mar 5, 2014 at 7:38
  • 1
    It is not the const problem but changing the type really -- whatever you do, it will always be a problem. Consider passing RichString, and then realizing you better pass String. Mar 5, 2014 at 7:51
  • 4
    @RobY: I am not sure what/whom you are addressing with latter and former. However: After that afternoon walking through the code, you should have learned you should refactor to const-correctness bottom-up, not top-down, i.e. start in the innermost units, and work your way up. Maybe your units were also not isolated enough, instead being tightly coupled, or you've fallen prey of inner systems.
    – phresnel
    Mar 5, 2014 at 8:06
  • 7
    "Const poisoning" isn't really a problem - the real problem is that C++ defaults to non-const. It's too easy to not const things that should be const because you have to opt into it instead of out of it.
    – Doval
    Mar 5, 2014 at 12:44
0

There are some philosophical problems in adding const to a language. If you declare const to a class, that means that the class cannot change. But a class is a set of variables coupled with methods (or mutators). We achieve abstraction by hiding the state of a class behind a set of methods. If a class is designed to hide state, then you need mutators to change that state from the outside and then it isn't const anymore. So it is only possible to declare const to classes that are immutable. So const seem only possible in scenarios where the classes (or the types you want to declare const) are trivial...

So do we need const anyway? I dont think so. I think that you can easily do without const if you have a good design. What data do you need and where, which methods are data-to-data methods and which abstractions do you need for I/O, network, view etc. Then you naturally split modules and classes arise that deal with state and you have methods and immutable classes that don't need state.

I think most problems arise with big fat data-objects that can save, transform and draw itself and then you want to pass it to a renderer for example. So you cannot copy the contents of the data, because that is too expensive for a big data-object. But you dont want it to change either, so you need something like const you think. Let the compiler figure out your design flaws. However if you split those objects in only an immutable data-object and implement the methods in the responsible module, you can pass around (only) the pointer and do things you want to do with the data while also guaranteeing immutability.

I know that it is possible in C++ to declare some methods const and to not declare on other methods, because they are mutators. And then some time later you need a cache and then a getter mutates an object (because it lazy loads) and it isnt const anymore. But that was the whole point of this abstraction right? You don't know what state gets mutated with each call.

3
  • 1
    "So const seem only possible in scenarios where the classes (or the types you want to declare const) are trivial..." Persistent data structures are immutable and non-trivial. You just won't see them in C++ because pretty much all of them share their internal data between multiple instances, and C++ lacks garbage collection to make that work. "I think that you can easily do without const if you have a good design." Immutable values make code a lot simpler to reason about.
    – Doval
    Mar 5, 2014 at 12:40
  • +1 thank you. Could you please clarify on "declare const to a class"? Did you mean setting class as a const? If yes, I am not asking about this -- C++ const works like a view, you can declare a const next to object, not a class (or something changed in C++11). Also there is a problem with the next paragraph and word "easily" -- there is a good question about C++-const in C# and the amount of work it involves is paramount -- for every type that you intend to put const (in C++ sense) you have to define interface, also for all properties. Mar 5, 2014 at 12:46
  • 1
    When you're talking about a "class" you actually mean "instance of an class", right? I think that's an important distinction.
    – svick
    Mar 5, 2014 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.