const attribute makes whole element const?
monarch_dodra
monarchdodra at gmail.com
Tue Sep 11 02:43:09 PDT 2012
On Tuesday, 11 September 2012 at 09:00:15 UTC, Ali Çehreli wrote:
> 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.
No arguments there. tests[4] first creates an element initialized
to the value of Test.init.
> [SNIP]
>
> 'this.Name = name' fails to compile for that reason.
>
> Ali
The difference is that the opAssign operator I defined
specifically does not attempt to modify the const member, so
assigning to an already existing object is legal.
Even with that though, I have:
void main()
{
Test t1;
Test[4] testsArray;
Test[int] tests;
t1 = Test("hello"); // (1)
testsArray[3] = Test("hello"); // (2)
tests[4] = Test("hello"); // (3)
}
In this program:
(1) compiles and is perfectly legal.
(2) ditto.
(3) This fails to compile, but it has no reason not to.
More information about the Digitalmars-d-learn
mailing list