Hi,

thanks for the reply...to answer your direct question, the original code 
looked like:


struct A
{
    int someInt;
}

struct Test
{
    @property { const(A) getA() { return mA; } }
    this( ref const(A) arg )
    {
        mA = arg;
    }

private:
    A mA;
}

void main()
{
    Test myTest1;
    A topA;

    void _someFunc( ref const(A) myA )
    {
        myTest1 = Test(myA);
    }

    Test myTest2 = Test(topA);      // is ok as expected
    _someFunc( topA );

    // later on....
    A foo = myTest1.getA();
}

which compiles. However, I think I exercised some other compiler-related 
bug when I added a field to another structure in the module, and the 
compiler started complaining about the construct above.......
'Error: cannot implicitly convert expression (arg) of type const(A) to A' 
in the constructor of Test (I'm unable to recreate this error in this 
simple code example).

(I am prototyping something, so the code I'm producing is very badly 
structured, and I have nested functions within delegates within .... and I 
have also hit some odd scoping errors - definite compiler issues - 
(notwithstanding the horrible code structure)).

....so (given my D knowledge is limited) I then wondered why it accepted 
(nonconst)mA=(const)arg in the first place, hence the const()...hence the 
original question.

I am assuming that the ref const(A) myA means that _someFunc (and below) is 
unable to alter any fields of myA. This may be my basic error.

thanks !






ketmar via Digitalmars-d-learn wrote:

> On Sat, 03 Jan 2015 13:25:31 +1030
> ted via Digitalmars-d-learn <digitalmars-d-learn@puremagic.com> wrote:
> 
>> 
>> I get the following error from the code below: (dmd2.066.1, linux)
>> test.d(26): Error: cannot modify struct myTest1 Test with immutable 
members
>> 
>> Is this expected?
>> 
>> If so, how can I achieve this result - being able to set (a new) initial
>> value of myTest1 from within an nested function ?
>> 
>> thanks !
>> ted
>> 
>> 
>> code:
>> struct A
>> {
>>     int someInt;
>> }
>> 
>> struct Test
>> {
>>     this( ref const(A) arg )
>>     {
>>         mA = arg;
>>     }
>> 
>> private:
>>     const(A) mA;
>> }
>> 
>> void main()
>> {
>>     Test myTest1;
>>     A topA;
>> 
>>     void _someFunc( ref const(A) myA )
>>     {
>>         myTest1 = Test(myA);
>>     }
>> 
>>     Test myTest2 = Test(topA);      // is ok as expected
>>     _someFunc( topA );                 // error.
>> }
> 
> the question is: "why do you want `mA` to be const?" leaving aside
> compiler complaints this is the one and important question. let's try
> to fix your code instead of devising workarounds to beat the
> compiler. ;-)
> 
> please remember that D `const` is not the same as C/C++ `const`, so my
> question is not so stupid as it may look.
> 
> p.s. you can use `in A myA` instead of `ref const A myA`, in most cases
> compiler is intelligent enough to use "pass-by-reference" for `in` args.

Reply via email to