On Sunday, 22 May 2016 at 19:29:59 UTC, Meta wrote:

Const *is* necessary to prevent _myVar being written to through code like:

f.myVar = 4;

Of course this isn't necessary for value types, but for reference types.



I was referring specifically to marking the function const, not the return type. Marking the return type const is highly context-dependent. It's perfectly reasonable to return a non-const class reference from a getter property. As long as the internal reference is private, it isn't going to be overwritten externally without a setter property. I don't see how it could be considered necessary. For a pointer, sure, to prevent *(bar.fooVer) = Foo(10). But for class references it's only necessary if you don't want the returned instances members to be modified.

It's also useful for value types, IMO, for preventing someone from doing this:

f.myVar = 4;

And wondering why the code has no effect.

The compiler already gives an error message describing the problem:

Error: function mod.Foo.myVar () is not callable using argument types (int)

How does const help here?

Reply via email to