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
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.
Right, this is not a compiler bug.
(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".
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.
*** This issue has been marked as a duplicate of issue 6336 ***