Skip to content

Commit fd911c0

Browse files
committed
[spec/struct] Add Member Functions section
Show that a method can be called on a struct rvalue. Fixes #4234.
1 parent b8dddee commit fd911c0

File tree

1 file changed

+33
-2
lines changed

1 file changed

+33
-2
lines changed

spec/struct.dd

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,9 @@ $(H3 $(LNAME2 struct-members, Struct Members))
104104
$(LI Fields)
105105
$(LI $(DDSUBLINK spec/attribute, static, Static) fields)
106106
$(LI $(RELATIVE_LINK2 anonymous, Anonymous Structs and Unions))
107-
$(LI $(DDSUBLINK spec/class, member-functions, member functions)
107+
$(LI $(RELATIVE_LINK2 member-functions, Member Functions)
108108
$(UL
109-
$(LI static member functions)
109+
$(LI $(DDSUBLINK spec/attribute, static, Static) member functions)
110110
$(LI $(RELATIVE_LINK2 struct-constructor, Constructors))
111111
$(LI $(RELATIVE_LINK2 struct-destructor, Destructors))
112112
$(LI $(RELATIVE_LINK2 Invariant, Invariants))
@@ -2127,6 +2127,37 @@ void main()
21272127
---
21282128
)
21292129

2130+
2131+
$(H2 $(LNAME2 member-functions, Member Functions (a.k.a. Methods)))
2132+
2133+
$(P A struct/union can have non-static member functions,
2134+
$(DDSUBLINK spec/class, member-functions, like classes).
2135+
Such functions have a hidden $(DDSUBLINK spec/expression, this, `this` parameter)
2136+
which is a reference to the struct instance. However, they can still be called
2137+
on an rvalue struct instance:)
2138+
2139+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
2140+
---
2141+
struct S
2142+
{
2143+
int i;
2144+
int f() => ++i;
2145+
}
2146+
2147+
void main()
2148+
{
2149+
//S().i++; // cannot modify, `S().i` is not an lvalue
2150+
assert(S().f() == 1); // OK
2151+
}
2152+
---
2153+
)
2154+
2155+
$(RATIONALE A method may have other side effects besides mutating a field,
2156+
or it may produce a useful return value. In the general case, throwing
2157+
away changes to a field after the method returns does not necessarily indicate
2158+
a logic error.)
2159+
2160+
21302161
$(H2 $(LEGACY_LNAME2 StructDestructor, struct-destructor, Struct Destructors))
21312162

21322163
$(P Destructors are called implicitly when an object goes out of scope, or

0 commit comments

Comments
 (0)