r/cpp • u/render787 • 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.
52
u/jtooker Jul 05 '18
Yes, but in some cases this the proper place - thank you for the writeup of some of the non-obvious pitfalls relating to moves.
I have used const with immovable objects, perhaps this should be recommended if going down this path (i.e. immutable -> immovable as a rule of thumb).
40
u/kalmoc Jul 05 '18 edited Jul 06 '18
Then he simply changes it to a non-const string - where is the problem? In particular changing an int into a string will require a lot of refactoring irrespective of wether it is const or not.
That doesn't invalidate your other points of course
3
u/NotAYakk Jul 05 '18
Why assume? Check. You'll want a non-small buffer based anyhow; when you run into a throwing move ctor, use the non-small buffer based version (which is nothrow).
Or if you don't want that, static assert it isn't a throwing move.
13
u/cleroth Game Developer Jul 05 '18
You can use quotes and code formatting on reddit. See this page.
13
u/tcbrindle Flux Jul 05 '18
The possibly non-
noexceptmove constructor isn't the worst part aboutconstmember variables. The worst part, as plenty of other people have mentioned, is that they can't be moved from (because of course, you can't change them!) -- any attempt to move them will just call the copy constructor or copy assignment operator. This doesn't matter for trivial types of course, but can be surprisingly expensive for types that do dynamic allocation on copy, especially if you think you're doing the right thing and usingstd::moveeverywhere.The best solution would be for C++ to have a destructive move operation, like that other language does. Then the compiler could turn off const in the "move destructor", as it does in ordinary destructors today, and
constmembers could be moved properly.I remember Sean Parent and a couple of other people talking about destructive move a couple of years ago, and I seem to recall a paper on it, but sadly it never got anywhere.
10
u/OldWolf2 Jul 05 '18
I learned pretty early on in my C++ career that
constnon-static member variables are more trouble than they are worth.17
u/kalmoc Jul 05 '18
I'd really like a "const except for move and assignment"
9
u/quicknir Jul 05 '18
I agree with this rule, and you covered the most "surprising" reason to do it, but not the main reason. More simply, your type is not going to be naturally move assignable, or swappable (by default). There's rarely a good reason for a type not to provide that functionality (immovable types are a very rare case).
Note that an extension of this rule, is to never have reference member variables: they are automatically const, of course. Reference member variables are worse in at least one way as well; at least with const member variables you can eventually decide to simply drop the const. With references, you have to change them to pointers and change every single usage of
.to->. Raw pointer member variables are also somewhat smelly, but if you're going to do something along those lines it's better to make a raw pointer member than a reference member (and enforce non-nullness in the constructor).2
u/doom_Oo7 Jul 05 '18
In my experience, 99.9 % of the time you're moving whole containers, and moving e.g. a std::vector won't call any copy or move constructor.
... then they'll change int into string ? what's the problem ?
In general, I'd much rather start with the safety of const members and risk a throwing move (I frankly never saw one in ~6 years of programming in C++11 and later) than the opposite.
4
u/jguegant Jul 05 '18 edited Jul 05 '18
I think the biggest issue is that kind of types are not copy assignable, unless you implement a copy assignment operator with really weird semantics (not really copying the const member). Not being copy assignable will forbid you to place an instance of this type into a vector. You may be able to do so if you don't insert/erase anything, but that's implementation defined.
2
u/Poddster Jul 05 '18
Why is this?
10
u/ericlemanissier Jul 05 '18 edited Jul 05 '18
The performance gap is quite huge indeed! emplace_back is more than 3 times slower when there is a const string member: http://quick-bench.com/T1F8RVgLMfUNtPCa3pryGDbEIEg
2
u/jc746 Jul 05 '18
If the member is move-only then making it const will prevent the class from being movable by default. For example it seems sensible to implement a pimple style class with a const unique_ptr that is initialized in the constructor because you can be sure the pointer is not null for the life of the object, but then your class will not get the compiler generated move functions.
2
u/Rseding91 Factorio Developer Jul 06 '18
In every case I've written a const member variable it implies immutability of the class/struct and also deleted the copy/move operator/constructor.
2
u/ronniethelizard Jul 06 '18
Could a modifier for class methods be made called mutable that would allow the method to modify const class members? This would be opposite to how declaring a method const restricts it from modifying nonmutable member variables.
1
u/tedbradly Mar 16 '22
Using const is bad if you need stuff like a move that is noexcept or the speed of a proper move rather than a copy. It's purely an efficiency and syntax thing. It's not bad due to enforcing an aspect of your API too low level on members. For example, you could have a const member that is never exposed through the API.
The intention of a const member is to convey that a member should never change after initialization, simplifying understanding the logic in the class. This additionally adds a compile-time check if someone attempts to change an unchangeable member. This design choice is sensible in some cases although it has unfortunate results with respect to how an object can be used and its efficiency.
It wouldn't even be far-fetched for the standard to add a new keyword that enforces constness on a member while allowing move to be generated and work efficiently. It probably won't happen since it would increase complexity for perhaps not much gain in terms of reducing the complexity of some classes, but the idea isn't outrageous like it would be if this claim were true that const functions replace the use case of const members.
A more honest criticism of using const members is you might wonder why that const member can't just be passed as a const argument in the API. Take a class whose entire state is const by design. That's basically a collection of pure functions with implicit arguments. There's no reason to hide an argument if it is central to viewing the input/output relationship of a method. In this scenario, a const member disguises what a method actually depends on and replaces the not so complicated ability to use bind if you want briefer function calls. With bind, you retain the input/output relationship and the briefer calls at the cost of a little boilerplate code.
1
u/nunchyabeeswax Oct 26 '23
Well, an API should not have access to member variables. In general, they should all be protected or private. So, making them const (if the design calls for it) is itself an implementation detail.
If a class or struct has an initial state (or part of its initial state) that is meant to remain constant for the duration of the instance, then it makes sense to make it const.
And if for some reason this is meant to be public, I would prefer a const member function returning that over making that member both const and public.
Law of Demeter people: if part of a state is not meant to change after its initialization, make it constant (in C++, by making the compiler treat it as such.)
1
u/Middlewarian github.com/Ebenezer-group/onwards Jul 06 '18
Most serialization libs don't support const members or reference members.
0
u/pravic Jul 06 '18 edited Jul 12 '18
Having that struct A:
A a = { "id", 7 }; A b = std::move(a);
Is really a copy-ctor here?
-6
u/cjxgm Jul 05 '18
My guideline is,
constcan only have 2 forms:T const*andT const&. No other places can useconst, unless semantically equivalent to the 2 forms above.-1
u/ericlemanissier Jul 06 '18 edited Jul 06 '18
Another benchmark, showing dramatic performance difference (*3.5) when calling std::vector::emplace_back with types having a const member vs only mutable member:
http://quick-bench.com/ZXe7-4sa1xjtg_lyAp9LVkz8t3Q
The same effect happens with all operations increasing vector capacity (push_back, emplace, resize, insert)
12
u/[deleted] Jul 05 '18 edited Jul 05 '18
[removed] — view removed comment