const and immutable member variables in classes
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 2 17:49:00 PST 2016
On Tuesday, February 02, 2016 14:48:03 Ali Çehreli via Digitalmars-d-learn wrote:
> const and immutable members make structs non-assignable:
>
> struct S {
> const int c; // Makes S non-assignable
> immutable int i; // Makes S non-assignable
> }
>
> void main() {
> auto a = S();
> auto b = S();
> a = b; // Compilation ERROR
> }
>
> (That is the same issue in C++.)
>
> That's why I've been avoiding them altogether. However, considering that
> there is no default-assignment for classes, there is no problem with
> using const or immutable members with classes, right?
Default initialization isn't really the issue. It's assignability in
general. Even if you @disabled default initialization in a struct, then
having a const or immutable member would be annoying, because you couldn't
assign it another value later. But in any case, no, classes don't have that
problem (at least not normally), because you don't assign to them. You just
assign to their references. So, you don't normally run into an issue where
you're trying to overwrite the state of a class object and aren't able to.
Now, you _can_ run into issues if you want to provide a way to overwrite the
whole state of a class object similar to assigning to a struct, but the
class would have to be specially written to support that via some kind of
non-standard function in order to support that, and you could just avoid
giving such a class any const or immutable members.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list