Structs with pointers?

Dmitry Olshansky dmitry.olsh at gmail.com
Sun Jan 23 08:55:02 PST 2011


On 23.01.2011 19:05, Mafi wrote:
> Am 23.01.2011 11:00, schrieb Dmitry Olshansky:
>> On 23.01.2011 2:02, bearophile wrote:
>>>> Is this another compiler bug?
>>> The situation is nice:
>>>
>>> struct Foo1 {}
>>> struct Foo2 { int x; }
>>> const struct Foo3 { int* p; }
>>> struct Foo4 { int* p; }
>>> void bar1(Foo1 f) {}
>>> void bar2(Foo2 f) {}
>>> void bar3(Foo3 f) {}
>>> void bar4(Foo4 f) {}
>>> void main() {
>>> const f1 = Foo1();
>>> bar1(f1); // no error
>>> const f2 = Foo2();
>>> bar2(f2); // no error
>>> const f3 = Foo3();
>>> bar3(f3); // no error
>>> const f4 = Foo4();
>>> bar4(f4); // error
>>> }
>>>
>>> Bye,
>>> bearophile
>>
>> The first two are actually OK, since you pass a copy of a value type
>> FooX to barX.
>> If signature was void bar(ref FooX) then it should have failed.
>> But the third makes me wonder what the *** is going on.
>>
>
> I think it's absolutely correct. Look: Foo3 is declared as const 
> struct meaning all it's members are const. We are passing a struct 
> like that to bar3:
>  const Foo3 { const int* p}
> which is implicitely converted to:
>  Foo3 { const int* p } //not ref !!
> Because it's not ref you can't manipulate the original struct anyways 
> and the pointer is still const. As long as you don't cast you cannot 
> change what the pointer points to so this implicit conversion is 
> correct IMO.
> It's like const(T[]) => const(T)[] .
Right, that makes sense.
But do we really need this syntax: const struct { ... }  ?
>
> Mafi

-- 

Dmitry Olshansky



More information about the Digitalmars-d-learn mailing list