Skip to content

Design note: const objects by default

Herb Sutter edited this page Apr 20, 2023 · 5 revisions

Q: Should objects be const by default?

A: For non-locals, yes!

One of the most frequent suggestions I get is to make objects const by default. I mostly agree!

In Cpp2, most objects are const by default. Most notably:

  • Parameters are const by default. For parameters, in is the default, and it not only implies const but it cannot be overridden to be mutable (if you want that, use inout which is a non-default).
  • Therefore, class member functions are const by default, because the explicit this parameter defaults to in (and therefore const) like all parameters.
  • (not yet implemented) I intend for non-local (global, static) objects to be implicitly constexpr.

But what about local variables? Get the arrows ready: I'm skeptical of the value of const by default for locals... maybe I don't get out enough, but the majority of local variables are, well, variables. And in my experience with the major C++ guidance literature, I don't remember often (or at all?) coming across guidance to make large numbers of local variables const... but maybe I missed it, so here's how to convince me: Show that in today's C++ guidance literature we already teach C++ programmers to make local variables const, and link to a few examples of such guidance (which will contain more details, including examples of problems that the advice avoids). That will start to make the case. If you can do that, feel free to open a "suggestion" issue about it!

Relatedly, people ask about distinguishing local variables as read-only or mutable using declaration syntax like val vs. var, or let vs. var. I'm not attracted to that mainly because they feel like they're adding concept count... I'm trying to avoid special one-off features that work in only one part of the language, and these feel to me like special one-off features that work only at local scope and basically duplicate the general features of mutable/const that we already have (and I'm happy to explore giving those shorter spellings, mut is kind of cute as a word, and if it works consistently throughout the language and not just at function scope then I'm open to it).