const attribute makes whole element const?
Ali Çehreli
acehreli at yahoo.com
Tue Sep 11 02:00:39 PDT 2012
On 09/10/2012 02:49 AM, monarch_dodra wrote:
> On Sunday, 9 September 2012 at 23:54:45 UTC, Jonathan M Davis
> wrote:
>>
>> [SNIP]
>>
>> the default assignment operator illegal. You could overload it, and as
>> long as
>> it doesn't touch any of the const member variables, it would work, but
>> the
>> const member variable is stuck as it is, and anything trying to
mutate is
>> illegal.
>>
>> [SNIP]
>>
>> - Jonathan M Davis
>
> Not to that it is my goal to be a pain, but the example I
> provided *does* overload opAssign (and the CC), but it *doesn't*
> work.
>
> Notice the error message is:
> "Error: tests[4] isn't mutable"
> Which is simply not true.
>
> The default assignment operator, when trying to do an assignment creates:
> "Error: variable XXX cannot modify struct with immutable members."
> But that is not what we are seeing.
>
> It appears that when writting:
> tests[4] = Test("Foobar");
> It *looks* like compiler is eliding the opAssign/CC completely,
> opting for a bit copy, which is illegal.
I don't see how opAssign is involved here. The problem is with the eager
element insertion of the following expression alone:
tests[4]
That expression does add an element having the default value to the
container. Try this program:
import std.stdio;
struct Test
{
string name;
}
Test alsoPrintLength(Test[uint] aa)
{
writefln("Adding to this AA: %s", aa);
return Test();
}
void main()
{
Test[uint] tests;
tests[4] = alsoPrintLength(tests);
}
The output:
Adding to this AA: [4:Test("")]
As it demonstrates, the AA already has an element when alsoPrintLength()
is called. The assignment in the last line of the program is assigning
to that element which happens to have a const member in your example:
struct Test {
const string Name;
this(string name) {
this.Name = name;
}
}
'this.Name = name' fails to compile for that reason.
Ali
More information about the Digitalmars-d-learn
mailing list