Struct reference returning function and const members

Ali Çehreli acehreli at yahoo.com
Wed Mar 2 22:47:11 PST 2011


On 03/02/2011 10:42 PM, Tom wrote:
> I have...
>
> int main(string[] args) {
> auto s1 = f(); // MH MH
> auto s2 = g(); // OK
> s2.c = null; // OK
> return 0;
> }
>
> class C {}
>
> struct StructWithConstMember {
> this(int i, C c) { this.i=i; this.c=c; }
> int i;
> const(C) c;
> }
>
> struct StructWithoutConstMember {
> this(int i, C c) { this.i=i; this.c=c; }
> int i;
> C c;
> }
>
> ref StructWithConstMember f() {
> return * new StructWithConstMember(1, new C); // ERROR
> }
>
> ref StructWithoutConstMember g() {
> return * new StructWithoutConstMember(1, new C); // OK
> }
>
>
> And get the error...
> src\main.d(27): Error: *new StructWithConstMember(1,new C) is not mutable
>
> So I can't return a struct that has a const member? Why? Am I missing
> something something?
>
> Thanks,
> Tom;

I don't know the full answer but returning a reference to const object 
works:

ref const(StructWithConstMember) f() {
     return * new StructWithConstMember(1, new C); // now compiles
}

Ali



More information about the Digitalmars-d-learn mailing list