Does opSlice work with immutable values?

anonymous anonymous at example.com
Mon Feb 24 10:45:33 PST 2014


On Monday, 24 February 2014 at 17:11:20 UTC, Joseph Cassman wrote:
> The const/immutable language spec page states that mutable and 
> immutable are implicitly convertible to const. Never thought 
> about this in the other direction though. And from what I 
> understand, the const keyword added to a function makes the 
> this pointer const. Can't see exactly why this works but it 
> does.

Implicit conversion from immutable to const is exactly what's
happening. It's not going the other direction.

The this pointer is passed to the method via a hidden parameter.
Qualifiers like const on methods really apply to that hidden this
parameter. Then, when you call a const method on an immutable
object, you really put an immutable object into a const
parameter. And that's fine, because immutable implicitly converts
to const.

In code:

struct S
{
       void m() const {}
}
immutable S s;
s.m();

is something like this behind the scenes:

struct S {}
void m(ref const S hidden_this) {}
immutable S s;
m(s);


More information about the Digitalmars-d-learn mailing list