www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Non-immutable char[] doesn't change?

reply "Salih Dincer" <salihdb hotmail.com> writes:
So, that's not this a bug?

   char[] a = [ 'a', 'b', 'c' ];
   char[] b = cast(char[])"abc";

   assert(a == b);       /* no problem! */
   assert(typeid(a) ==
          typeid(b));    /* no problem! */

// v--- TOGGLE CODE
   //a[0] = 'A';         /*
   b[0] = 'A';           /* there is problem:
                          * Segmentation fault
                          */

Thanx...
Aug 18 2012
next sibling parent reply "Salih Dincer" <salihdb hotmail.com> writes:
This may be the solution...:)

   char[] b = cast(char[])"abc".dup; // ok, unique reference

Sorry...
Aug 18 2012
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 08/18/2012 02:15 PM, Salih Dincer wrote:
 This may be the solution...:)

 char[] b = cast(char[])"abc".dup; // ok, unique reference

 Sorry...

You don't need the cast in this case. Topic: It is not a bug, but it might be surprising because the behaviour of typeid is different with polymorphic types. Typeid on a class object gives you back the RTTI structure of the value's type, while typeid on anything else gives you back the RTTI of the statically determined variable type. The reason this works this way is because class objects are the only objects which actually carry runtime type information with them.
Aug 18 2012
prev sibling parent "Maxim Fomin" <maxim maxim-fomin.ru> writes:
On Saturday, 18 August 2012 at 11:35:59 UTC, Salih Dincer wrote:
 So, that's not this a bug?

   char[] a = [ 'a', 'b', 'c' ];
   char[] b = cast(char[])"abc";

   assert(a == b);       /* no problem! */
   assert(typeid(a) ==
          typeid(b));    /* no problem! */

 // v--- TOGGLE CODE
   //a[0] = 'A';         /*
   b[0] = 'A';           /* there is problem:
                          * Segmentation fault
                          */

 Thanx...

"abc" in that position is a string literal. String literals may be placed in write-protected memory (mentioned in web page about dmd on linux). Anyway, type of "abc" is immutable(char)[] and casting just throws immutable away and doing this (even more writing to them) is a bad idea.
Aug 18 2012