Implicit conversion of concatenation result to immutable

Steven Schveighoffer schveiguy at gmail.com
Thu Apr 1 22:29:44 UTC 2021


On 4/1/21 5:59 PM, H. S. Teoh wrote:

> Now, when you append a string to a const(char)[], the compiler has to
> promote `string` to `const(char)[]` first, so that the operands of ~
> have the same type. And obviously, the result of concatenating two
> const(char)[] must be const(char)[], since you don't know if one of them
> may have mutable aliases somewhere else.  So the result must likewise be
> const(char)[].

But it's not.

auto z = x ~ y;
pragma(msg, typeof(z)); // char[]

This is what's confusing me. The compiler somehow knows it can do this 
implicit cast, but doesn't know that the result is unique. It should be 
obvious.

> One may argue that appending in general will reallocate, and once
> reallocated it will be unique, and there safe to implicitly convert to
> immutable.  However, in general we cannot guarantee this, e.g., one of
> the strings could be empty and not reallocate at runtime, so it may
> continue to be aliased by some mutable reference somewhere else. So the
> result must be typed as const(char)[], along with the restriction that
> it cannot implicitly convert to immutable.

a ~ b will always allocate new memory, it's in the spec.

-Steve


More information about the Digitalmars-d mailing list