Skip to content

Design note: const objects by default

Herb Sutter edited this page Oct 2, 2022 · 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).
  • (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!