Question about wchar[]

Steven Schveighoffer schveiguy at yahoo.com
Mon Feb 4 10:28:43 PST 2013


On Mon, 04 Feb 2013 13:13:22 -0500, ollie <ollie at home.net> wrote:

> I am using wchar[] and find the usage clunky. Am I doing something wrong?
>
> Example:
>     // Compiler complains that wchar[] != immutable(char)[]
>     wchar[] wstr = "This is a wchar[]";

It's not so much the wchar vs. char, but the mutable vs. immutable. It  
could be argued that the message should say "wchar[] != wstring" instead.

This works:

immutable(wchar)[] wstr = "This is a wchar[]";

or

wstring wstr = "This is a wchar[]";

> 	
>     // Compiler accepts this
>     wchar[] wstr = "This is a wchar[]"w.dup;

Right, because you are duplicating the string onto the heap, and making it  
mutable.

>
>     // Compiler accepts this
>     wchar[] wstr;
>     wstr ~= "This is a wchar[]";
>
> If the compiler knows the type in the last example with concatenation,
> shouldn't it be able to figure that out in the first example.

No, because the first example does not involve heap allocation, just  
straight assignment.

Appending involves concatenation, and making a copy of the original, so it  
is safe to do so.

-Steve


More information about the Digitalmars-d-learn mailing list