Using replaceInPlace, string and char[]

TSalm via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 15 01:47:31 PDT 2015


On Saturday, 15 August 2015 at 08:07:43 UTC, Ali Çehreli wrote:
> This looks like a bug to me. The template constraints of the 
> two overloads are pretty complicated. This case should match 
> only one of them.
>
Yes I understand. I've used ldc2. With DMD (v0.067.1) the error 
is more clear :
inout.d(11): Error: std.array.replaceInPlace called with argument 
types (char[], uint, uint, char[]) matches both:
/usr/include/dmd/phobos/std/array.d(2214):     
std.array.replaceInPlace!(char, char[]).replaceInPlace(ref char[] 
array, uint from, uint to, char[] stuff)
and:
/usr/include/dmd/phobos/std/array.d(2247):     
std.array.replaceInPlace!(char, char[]).replaceInPlace(ref char[] 
array, uint from, uint to, char[] stuff)
Must create a ticket for it ?

> > Don't understand why this doesn't work: it compiles fine and
> runs
> > perfectly if I change "char[]" by "string"
>
> You mean, this:
>
> import std.array;
> import std.stdio;
>
> void main()
> {
>     string a = "mon texte 1";    // <-- now string
>     writeln(a.ptr);              // added
>     char[] b = "abc".dup;
>     size_t x   = 4;
>     size_t y   = 9;
>     replaceInPlace( a, x , y, b );
>     writeln( a );
>     writeln(a.ptr);              // added
> }
>
> The output:
>
> 4BC480
> mon abc 1
> 7FC2AB867210    <-- different
>
> > ... don't understand why
> > since the documentation says :
> >        String literals are immutable (read only).
> >
> > How this function can change a type that is immutable ?
>
> It cannot change the characters of the original string. 
> replaceInPlace takes its first parameter by reference. What 
> changes is 'a' itself. As evidenced by the output of the 
> program, 'a' is now a slice to a new set of immutable 
> characters.
>
> If there were other slices to "mon texte 1", they wouldn't see 
> a change.
>
Yes I understand, thanks. In the other hand using "string" is not 
efficient since this certainly make a copy of the original 
string. Right ?
This is better to use "replaceInPlace" with "char[]", but this 
doesn't actually work :-(




More information about the Digitalmars-d-learn mailing list