Suggestion: safeguarding mutable structs #3252
-
We are all aware of the dangers prevented by mutable structs. The internet is full of posts warning about it or telling how someone got burned by it. However, mutable structs are necessary / appropriate in some cases, such as SpinLock. And when used as fields in classes they are perfectly safe as long as you don't accidentally copy them. After all, having an int inside a mutable struct field is not very different from just putting the int directly as a field in the class and adding the change methods to the class instead of the struct. Putting the int directly in the class just has less encapsulation and makes your design messier. My suggestion is simply to add a compiler warning when a mutable struct is assigned / copied. This should eliminate 99% of the problem. If someone did want to make a mutable struct that is copyable, they could add a constructor that copies it's state from an argument (the arg would have to be passed by ref). Caveat: I'm not a compiler person or a language guru, so ... please go easy on me when you think of all the challenges with this idea! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Also, how does the compiler figure out whether a What types other thank |
Beta Was this translation helpful? Give feedback.
-
I agree, having a NotCopyable field attribute that generates a compiler warning on copy would solve the problem. The reference is https://github.com/ufcpp/NonCopyableAnalyzer Let’s do it! |
Beta Was this translation helpful? Give feedback.
ValueTuple
s are mutablestruct
s. And so is e.g.System.Drawing.Point
. I don't think warning on every copy of those types is reasonable.Also, how does the compiler figure out whether a
struct
is immutable? We now havereadonly struct
, but not every immutablestruct
is going to be marked as such.What types other thank
SpinLock
are problematic? Maybe just a subset of all structs should be prevented from being copied? The issue #859 discusses exactly that and it even links to an analyzer which produces an error when a non-copyablestruct
is copied.