r/cpp • • Jul 05 '18

Coding Guideline: Avoid const member variables

Avoid using the const keyword with member variables of a class or struct type.

For a class type, if a piece of data is not supposed to change after being initialized, enforce this by design of the public API, not via the `const` key word.

For a struct which is a "dumb aggregate", it isn't appropriate to use `const`.

Using `const` on a member variable can force your class to have a throwing move. For instance this class,

struct A {
    const std::string id;
    int foo;
};

has a throwing move, because the use of `const` keyword on the member variable prevents the compiler from using the move constructor of `std::string` with `id`, instead the compiler generated move constructor for `A` will invoke the copy constructor of `A::id`, which can throw.

Even if your member variable does not have a throwing copy constructor, e.g.,

struct A {
    const int id;
    int foo;
};

you should still not use `const` -- what if someone later has to refactor `id` to be a `std::string` instead of an `int`? They might be forced down a rabbit hole of unnecessarily complex refactors, or have to accept a throwing move, which can cause incompatibility with some containers, or a significant performance hit if used with `std::vector` for instance.

In general, using `const` in a member variable is bad because you are enforcing an API invariant at too low a level -- you are enforcing it at so low a level that it interferes with move semantics. Typically there are reasonable alternatives.

If you want to implement a map that can be a drop-in replacement for `std::map`, don't use `std::pair<const Key, Value>`, instead store both Key and Value as mutable, and return the user a pair of references, the first of which is const: `std::pair<const Key &, Value &>`.

`const`-correctness is great -- use it on function parameters, class member functions, function local variables, etc. Avoid it on member variables of a class-type.

If your class is immovable by design then you can ignore this guideline

---

Would be interested in your reaction to this.

AFAIK a large majority of the examples I've seen where types "naturally" have throwing moves are caused by `const` member variables.

In code bases where I work and have worked in the past, most if not all types to have non-throwing moves, and we have implemented alternate versions of e.g. `std::function` that are type-erased and no-throw move constructible and assume the function objects are no-throw move constructible. In many of these cases it is important to us to do this because the application has real-time constraints and we care a lot about eliminating unnecessary dynamic allocations -- typically a throwing move happens because a dynamic allocation is happening when we don't want it to, so we have designed a lot of infrastructure in a way to force programmers not to do that. (Contrast this with @quicknir's comment here for instance https://www.reddit.com/r/cpp/comments/8vzvkb/be_mindful_with_compilergenerated_move/e1s24ac/ not that he's wrong ofc, we're just solving a more restricted problem and then we can do it with small buffer optimization and without throwing move)

I'm expecting that at some point we are going to run into obscure and painful problems around this, because I think the committee thought a lot when they decided to embrace throwing moves, but it hasn't happened to us yet.

I'm very interested to see which of these scenarios plays out:

1.) Embracing throwing moves in the stdlib is something that is necessary primarily for backwards compatibility, while code bases that have special needs and rely less on stdlib can avoid it practically all of the time,

2.) For fundamental reasons, avoiding throwing moves won't really work, eventually we will start to hit walls where certain types or idioms cannot be implemented without throwing moves and we will have to back out or implement alternate pathways to support this etc.

98 Upvotes

69 comments sorted by

View all comments

Show parent comment

-1

u/ripper37 Jul 06 '18

I wasn't saying that this benchmark doesn't make any sense. I'm simply showing that:

emplace_back is more than 3 times slower when there is a const string member

is a lie here and can lead to false conclusions, especially by those that are not proficient enough with the language to know why is there such a difference in performance and repeating a lie that emplace_back() is very slow. No it's not. The difference here is when we can move and where we can copy. In most cases move is much cheaper, so it's preferred, but saying that using const members is 3x slower is false - it's not. In some cases, due to more copies then move, it can be 3x slower, 10x slower, or exactly the same. This is not a real life scenario and I think that it is important to note in such benchmarks details like this so that everyone can make proper conclusions. Also - it only partially prohibits efficient moves (as stated earlier) - if your object is dynamically allocated and held by (for example) unique_ptr, then this probably won't affect you at all (performance wise).

I for one prefer cleaner and easier to understand/argue code and avoiding premature optimization. If something is slow because it is copied thousands of times instead of moves, then measure, find and optimize it. If this is one object that is not moved anywhere - no sense in making such optimization too early.

In the end - final argument - you can always remove const, but adding it might be very hard in some cases. If you know that some member is set in ctor and must not change for object's lifetime, then I'd recommend to put const there. If this is problematic, you can always wrap it so that access to it is const (can't change this value) but can move from it (which obviously can change this value, but nobody should ever move-from value just to change it so less options to screw something up by accident).