Why doesn't C# offer constness akin to C++?

前端 未结 5 1426
悲哀的现实
悲哀的现实 2021-02-07 12:53

References in C# are quite similar to those on C++, except that they are garbage collected.

Why is it then so difficult for the C# compiler to support the following:

5条回答
  •  你的背包
    2021-02-07 13:18

    As Jon already covered (of course) const correctness is not as simple as it might appear. C++ does it one way. D does it another (arguably more correct/ useful) way. C# flirts with it but doesn't do anything more daring, as you have discovered (and likely never well, as Jon well covered again).

    That said, I believe that many of Jon's "theoretical reasons" are resolved in D's model.

    In D (2.0), const works much like C++, except that it is fully transitive (so const applied to a pointer would apply to the object pointed to, any members of that object, any pointers that object had, objects they pointed to etc) - but it is explicit that this only applies from the variable that you have declared const (so if you already have a non-const object and you take a const pointer to it, the non-const variable can still mutate the state).

    D introduces another keyword - invariant - which applies to the object itself. This means that nothing can ever change the state once initialised.

    The beauty of this arrangement is that a const method can accept both const and invariant objects. Since invariant objects are the bread and butter of the functional world, and const method can be marked as "pure" in the functional sense - even though it may be used with mutable objects.

    Getting back on track - I think it's the case that we're only now (latter half of the naughties) understanding how best to use const (and invariant). .Net was originally defined when things were more hazy, so didn't commit to too much - and now it's too late to retrofit.

    I'd love to see a port of D run on the .Net VM, though :-)

提交回复
热议问题