Associative Array of Const Objects?

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 29 12:04:30 PDT 2015


On Sunday, 29 March 2015 at 18:43:32 UTC, bitwise wrote:
> I'm a little confused at this point why this doesn't work 
> either:
>
> const(Test) test = new Test();  // fine
> test = new Test();                     // error
>
>
> In C++, There is a clear distinction:
>
> const Test *test1 = nullptr; // const before type
> test1 = new Test();      // fine
> 	
> Test *const test2 = nullptr; // const before identifier
> test2 = new Test();      // error: test2 is readonly
>
> Isn't there such a distinction in D?

Notice how you have that '*' there that allows you to distinguish 
the data from the reference.

You can have a mutable pointer to const data in D, too:

struct Test {}
const(Test)* test1 = null;
test1 = new Test; /* fine */
const(Test*) test2 = null;
/* equivalent variant: const Test* test2 = null; */
test2 = new Test; /* Error: cannot modify const expression test2 
*/

You cannot have a mutable class object reference to const data, 
because syntactically that distinction isn't made in D. There is 
std.typecons.Rebindable, though:

import std.typecons: Rebindable;
class Test {}
Rebindable!(const Test) test = null;
test = new Test; /* fine */

> I would have suggested that I got things backward, but this 
> doesn't work either:
>
> const Test test = new Test();
> test = new Test(); // error: cannot modify const expression

`const Test test` is the same as `const(Test) test`.


More information about the Digitalmars-d-learn mailing list