2 ms·
> Data members: Never const > What good is a value-semantic Employee class if you can’t assign or swap values of that type? Question from a Java guy: Is immut
by xg15 5y ago
> Data members: Never const
> What good is a value-semantic Employee class if you can’t assign or swap values of that type?
Question from a Java guy: Is immutability not a thing in C(++) land?
Seems to me most modern high-level languages strive to make structs with "value" semantics immutable, i.e. members are set once on creation and then never changed. You're supposed to interact with those structs through pointers, so most usecases for copying or overwriting a struct don't apply.
I get that this doesn't translate fully well to C's programming model where you seem to interact a lot more with the actual data structures (and not just pointers). But wouldn't the ability to restrict arbitrary changes to a struct still be important?
- clappski 5y ago> But wouldn't the ability to restrict arbitrary changes to a struct still be important? Typically immutability in C++ is at the interface scope rather than structural, e.g. prefer this struct MyType { int x_; MyType( int x ) : x_( x ) {} }; void do_the_thing( const MyType& mt ); // mt.x_ = 1; doesn't compile, mt is const over this struct MyType { const int x_; MyType( int x ) : x_( x ) {} }; void do_the_thing( MyType mt ); // mt.x_ = 1; doesn't compile, x_ is const
- gpderetta 5y agoIn c++ you normally interact with value types by copying them around. Same way you would do for an int for example. Immutability is enforced with a top level const.