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
}
src\main.d(27): Error: *new StructWithConstMember(1,new C) is not mutable
Comment #1 by smjg — 2011-03-03T07:24:09Z
It only makes sense that it should make it const - to reassign the struct would violate the constancy of the const member. Though the MBNR approach (see issue 2625) would also work.
Comment #2 by bugzilla — 2012-01-24T00:06:54Z
Right, this is not a compiler bug.
Comment #3 by k.hara.pg — 2012-01-24T05:20:27Z
(In reply to comment #2)
> Right, this is not a compiler bug.
No, this is a compiler bug.
(In reply to comment #1)
> It only makes sense that it should make it const - to reassign the struct would
> violate the constancy of the const member.
A returned value from f() is *mutable* object, so to reassign the part of it is still valid.
f().i = 10; // field i is mutable so this code should compile.
This issue is a dup of bug 6366, that has more better summary "Issue 6336 - Can't return ref T where T has const/immutable members".
Comment #4 by k.hara.pg — 2012-01-24T05:22:57Z
Notice:
A NewExpression like (new StructWithConstMember(1, new C)) makes rvalue, but dereferencing it (* new StructWithConstMember(1, new C)) makes *lvalue*.
So returning it from function by ref is valid.
Comment #5 by k.hara.pg — 2012-01-24T05:23:21Z
*** This issue has been marked as a duplicate of issue 6336 ***