D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 5690 - Struct const member makes struct const
Summary: Struct const member makes struct const
Status: RESOLVED DUPLICATE of issue 6336
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: Other Windows
: P2 normal
Assignee: No Owner
URL:
Keywords: spec
Depends on:
Blocks:
 
Reported: 2011-03-03 05:34 UTC by Tom
Modified: 2012-01-24 05:23 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Tom 2011-03-03 05:34:25 UTC
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 Stewart Gordon 2011-03-03 07:24:09 UTC
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 Walter Bright 2012-01-24 00:06:54 UTC
Right, this is not a compiler bug.
Comment 3 Kenji Hara 2012-01-24 05:20:27 UTC
(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 Kenji Hara 2012-01-24 05:22:57 UTC
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 Kenji Hara 2012-01-24 05:23:21 UTC

*** This issue has been marked as a duplicate of issue 6336 ***