const attribute makes whole element const?

Ali Çehreli acehreli at yahoo.com
Sun Sep 9 16:47:48 PDT 2012


On 09/09/2012 08:09 AM, Namespace wrote:
 > On Saturday, 8 September 2012 at 23:18:14 UTC, Timon Gehr wrote:
 >> On 09/09/2012 01:16 AM, Namespace wrote:
 >>> Why fail this code?
 >>> without "const" on "Name" it works fine.
 >>>
 >>> http://dpaste.dzfl.pl/9fa0986a
 >>
 >> const fields cannot be written to. This includes the case when the
 >> entire struct is written to at once.
 >
 > But i assign the const attribute in the ctor.

The constructor is not involved in that syntax.

 > So this behaviour doesn't  make any sense...

The problem is with the internal workings of the marked line below:

     struct Test {
         const string Name;
         // ...
     }

     Test[string] tests;
     // ...
     tests[4] = t4;    // <--

tests[4] is an expression that automatically creates a default Test 
object and associates that default object with key 4. Then the line 
above becomes an assignment on top of that object, which can't happen 
because of the const member.

Associative arrays must have an insert() function if it does not already 
exist:

     tests.insert(4, t4);    // does this exist?

Ali



More information about the Digitalmars-d-learn mailing list