CppCoreGuidelines icon indicating copy to clipboard operation
CppCoreGuidelines copied to clipboard

Immutable vs regular

Open hsutter opened this issue 4 years ago • 19 comments

The Guidelines recommend

  • using immutability/const
  • using concrete types
  • that concrete types should be regular (C.11)

A question arose: What should C,11 say about a type that is both immutable and concrete? Such a type cannot be regular because it might be copy constructible, but it can't be copy assignable.

The Guidelines discourage some techniques that lead to such types, such as "C.12: Don’t make data members const or references." But some users do find immutable copyable types useful, and the Guidelines as written appear to ban them.

If we want to account for immutable copyable types, a suggestion was to add an Exception to "C.11: Make concrete types regular" along the lines of the following:

Note Immutable types cannot be assigned, so they can't be regular; they may be copy-constructible only.

This text mirrors the existing Note in the same Guideline:

[EXISTING NOTE] Note Handles for resources that cannot be cloned, e.g., a scoped_lock for a mutex, are concrete types but typically cannot be copied (instead, they can usually be moved), so they can’t be regular; instead, they tend to be move-only.

hsutter avatar May 30 '22 00:05 hsutter

C.12 seems in conflict with P.10. const on data members is very useful to cut down on bugs for reasons in P.10, but I suspect the aim was to have it only apply to concrete types? in which case we should refine C.12 to read like its siblings C.10 and C.11 and mention "concrete types" explicitly in the rule name.

apenn-msft avatar May 30 '22 00:05 apenn-msft

The Guidelines discourage some techniques that lead to such types, such as "C.12: Don’t make data members const or references." But some users do find immutable copyable types useful, and the Guidelines as written appear to ban them.

From the trenches, this can be good because const data members can make types difficult to use because ... they aren't regular. The example in C.11 is:

struct Bundle {
    string name;
    vector<Record> vr;
};

An immutable version of the type would be something like:

struct ImmutableBundle {
    const string name;
    const vector<Record> vr;
};

Creating objects of each:

const Bundle b {"fred", {r1, r2}};
ImmutableBundle ib {"fred", {r1, r2}};

Both b and ib are immutable. Is there an advantage of enforcing immutability at the type level vs. object level?

bgloyer avatar Jun 02 '22 06:06 bgloyer

The advantage is that inside void foo(ImmutableBundle& ib) you can be (almost*) certain that ib is not going to change. No matter what functions you call, no matter what other threads are on the system. With void foo(const Bundle& b) you dont have that guarantee.

*) It could still be destructed (and even recreated at the same location)

MikeGitb avatar Jun 02 '22 07:06 MikeGitb

or in general const gives us the power as class designers to define invariants that should not change for the class lifetime. that is irrespective of whether the class user (the owner of the object) decides whether the entire object should be an invariant. For example, as a class designer, I can make a "Wheel" with a fixed radius that can rotate. Users of my class may or may not decide to allow the wheel to be Rotate-able (i.e. Wheel w; vs const Wheel w;), however as the class designer I know the wheel should never change size and so I can prevent an entire class of bugs by marking the radius as an invariant (as const).

struct Wheel
{
  Wheel(double radius) : m_radius{radius} {}
  void Rotate() { m_radius++; } // oops!
private: 
  double m_radius;
  double m_rotations = 0;
}

It's an unfortunate outcome of C++ syntax/mechanics that we cannot have both - we either have robust types that have invariants and make common usage patterns difficult, or we have concrete types that are easy to use but less robust.

Ideally what would be nice would be for C++ to either a) ignore const qualifications on class members when copy assigned or a more general solution (and probably be more feasible along the lines of syntax sugar) would be to b) have an "in place" copy assignment operator, where 'a1 = a2' is shorthand for similar to what std::optional::emplace does: a1.~A(); new (&a1) A(a2); i.e. destruct a1, allocate a new A in the same memory and copy construct it from a2.

apenn-msft avatar Jun 03 '22 03:06 apenn-msft

Personally, I don't think "avoid mistakes when implementing a class" is a good reason to make a member const. Stuff like that (assigning/ modifying the wrong member variable) usually pops up almost immediately during testing.

MikeGitb avatar Jun 03 '22 06:06 MikeGitb

@MikeGitb Could you comment on whether you think this is true of const correctness in general? Personally I don't see a difference. I think there is a temptation in class design to assume that everyone modifying a class knows exactly how it works and tests it thoroughly and everyone using the class doesn't know how it works (internally). The reality for most classes, in my experience, is that the line between author and user is a lot more blurred and test coverage is a lot more inconsistent.

I think it's important to remember that it's not just a question of maintaining invariants when you originally write the class. Those invariants need to hold through future modifications to the class. I can't write a test which guarantees that no future method added to Wheel won't mutate m_radius. Similarly I am not confident that a colleague modifying Wheel will add appropriate tests which verify not just that the behavior they've added has the effect it's supposed to but also that it hasn't negatively affected unrelated observable behavior. Of course I also can't guarantee that they won't just remove the const but at least the signal is there for them to consider or ignore.

shaneasd avatar Jun 03 '22 08:06 shaneasd

I can't write a test which guarantees that no future method added to Wheel won't mutate m_radius.

I'd argue you shouldn't write such a test at all. What you should test instead is that your Wheel class does whatever wheels in your domain are supposed to do. If someone mutates m_radius in the future iteration of your class and yet it still performs its function correctly then why should you care?

Similarly I am not confident that a colleague modifying Wheel will add appropriate tests which verify not just that the behavior they've added has the effect it's supposed to but also that it hasn't negatively affected unrelated observable behavior.

More often than not your colleagues shouldn't have to write tests that verify that their change hasn't negatively affected unrelated observable behavior. That's what the existing tests are for. The presence of the appropriate tests should be the basic requirement for passing the code review, IMO.

atomicflag avatar Jun 03 '22 11:06 atomicflag

@MikeGitb Could you comment on whether you think this is true of const correctness in general? Personally I don't see a difference.

I might be able to give you a better answer when you tell me, what exactly you consider "const correctness in general". But, if we compare making a member variable const with making a reference parameter of a function const, then we see that the former has a negative impact on usability (the type can't be made regular without some tricks anymore), whereas the latter makes the function more usable (we can pass const objects and temporaries). And with regards to scope, a const member only benefits the people modifying that type, whereas changing the signature of a function benefits everyone using that function. Making local variables const is somewhere between where it is a low effort, low impact situation: It only impacts the people modifying the function, and is nutral with respect to usability.

So yes, I see quite a big differences between different sorts of "make things const when they are not supposed to be mutated".

MikeGitb avatar Jun 03 '22 13:06 MikeGitb

In response to @coffee-lord Suppose I wrote a fixed (at runtime) capacity vector type which preallocated memory for its full capacity. I still need to store the capacity to know whether I can add elements but there is an invariant that the size of the allocated memory correspond to the capacity. Logically, as it's a fixed capacity vector, I may want to make the capacity const. Let's say that I do not do this. I do, however add a bunch of unit tests that verify my class works as expected under all currently possible circumstances.

Now one of my colleagues adds a public method to the class that (through lack of care or lack of understanding) modifies the capacity. When that method is called it's going to break the object. An object in that state would no longer pass my tests but my tests can't put the object in that state as that would require calling a method that didn't exist when I added my tests.

Naturally what should happen in this circumstance is that as part of the change to add the problematic method, comprehensive unit tests should be added which prove that it does what it wanted to do and doesn't break anything else. This is a nice ideal to aspire towards but it can't always be relied on. What I'd like to be able to do is design my class in a way that makes it not just hard to misuse from outside but also hard to unintentionally break from inside. I would say that preventing breakages that could in principle have been detected by automated tests is a key reason for the existence of const (and many other features of the language and tools).

In response to @MikeGitb That's fair. I agree it's a spectrum of usefulness and of cost and I agree with where you've positioned the different uses of const on that spectrum. I guess where I would disagree would be on the relative merit of the type being regular but I don't disagree that that has value.

shaneasd avatar Jun 03 '22 15:06 shaneasd

Now one of my colleagues adds a public method to the class that (through lack of care or lack of understanding) modifies the capacity. When that method is called it's going to break the object. An object in that state would no longer pass my tests but my tests can't put the object in that state as that would require calling a method that didn't exist when I added my tests.

This is one reason I have shied away from using private sections of a class and relying more on protected sections so that I can derive classes in tests that can mutate it in unexpected ways and validate that things don't break in ways they were not suppose to.

Also, this is why code must be documented. The code states what is happening, but the documentation gives the intent, purpose, warnings, etc. Code by itself is not complete.

BenjamenMeyer avatar Jun 03 '22 15:06 BenjamenMeyer

@shaneasd

Logically, as it's a fixed capacity vector, I may want to make the capacity const.

If it's a fixed capacity non-copy assignable and non-move assignable vector then I suppose I would agree with that statement. Otherwise you would have no choice but to leave the capacity as a non-const variable. (The rest of what you said still applies though). I remember you weren't too fond of C.11 and I wasn't really trying to change your mind.

My original point was more about a test that's designed to limit which private variables future implementations can and can't mutate (something like the infamous #define private public).

atomicflag avatar Jun 03 '22 18:06 atomicflag

Interesting to note C.67: A polymorphic class should suppress public copy/move and ES.63: Don’t slice in relation to this issue. C.67 would prevent any type with a virtual member and any class which acts as a base class from being regular. This suggests that the priorities are polymorphism > regular types > expressing immutability of members

This is certainly a valid prioritization and I'm not necessarily expecting to change anyone's mind with this observation but it does mean that:

  • There is precedent in the guidelines for sacrificing regularity in favor of other priorities
  • In cases where the c;ass in question is already affected by C.67 or ES.63 you lose the benefit of regularity when applying C.12.

shaneasd avatar Jul 04 '22 00:07 shaneasd

This suggests that the priorities are polymorphism > regular types

Neither is necessarily better, they're just mutually exclusive. A type can be polymorphic or be a value type (and in the latter case should be regular), it should not try to be both.

hsutter avatar Jul 06 '22 22:07 hsutter

Sure, classes containing immutable data and classes that are polymorphic are, by necessity, not regular. What I was trying to say is, if you start with a recommendation that types should be regular, the current rules make an exception for polymorphic classes but not classes with immutable data.

If we would benefit from making a class polymorphic we do so (or at least are permitted to do so) sacrificing regularity. If we would benefit from giving a class immutable members we decline to do so because it would sacrifice regularity.

shaneasd avatar Jul 07 '22 11:07 shaneasd

I think that is comparing apples to oranges. Polymorphism an regularity are interface design properties (An immutable datastructure would be too). Having a const member is an implementation detail.

MikeGitb avatar Jul 07 '22 13:07 MikeGitb

Question for the experts: Is the following legal in c++ (i.e. can you make a type regular despite having a const member)?

struct Foo { 
     private:
         const int i; //we don't allow pointers to this member variable to escape the type 
     public:
          Foo& operator=(const Foo& other){ 
               this->~Foo(); 
               new(this) Foo(other);
               return *this;
           }
           // constructors
           // ...
  };

Not that I'd recommend it, even if it was.

MikeGitb avatar Jul 07 '22 13:07 MikeGitb

@MikeGitb that's covered by https://eel.is/c++draft/basic.memobj#basic.life-8

for const members it was prohibited in C++17 https://timsong-cpp.github.io/cppwp/n4659/basic.life#8.3 but prohibition could be laundered away and was removed entirely by C++20 https://timsong-cpp.github.io/cppwp/n4861/basic.life#8.3 due to RU007

cubbimew avatar Jul 07 '22 15:07 cubbimew

That means this is legal in C++20? It looks like this can be used as the "in place" copy assignment operator @apenn-msft mentioned.

Is it safe to do?

bgloyer avatar Jul 09 '22 18:07 bgloyer

Editors call: Thanks! We think the source of the confusion might be distinguishing between a type and an object of that type. A const object of a regular type is also not copy-assignable. An immutable type should just behave as though all its objects are const. If mandating that all objects of a type are effectively const, that's fine -- we think there is no tension between the concepts of immutablity and regularity.

hsutter avatar Jul 13 '22 16:07 hsutter