Struct reference returning function and const members
Jonathan M Davis
jmdavisProg at gmx.com
Wed Mar 2 23:25:44 PST 2011
On Wednesday 02 March 2011 22:42:18 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?
Well, it has something do to with the ref, since passing be value works. I'm not
sure if it's a bug or not. On the whole, I would _not_ advise that you have
structs with const or immutable member variables. You can never reassign to
them. And that may be related to why it's not working here. It may very well be
a bug - I sure don't know why it isn't working here - but in general, having
structs with const or immutable members probably isn't a good idea.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list