Skip to content

Commit d4d306c

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

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

spec/struct.dd

Lines changed: 35 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,39 @@ 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 (called instance methods) have a hidden
2136+
$(DDSUBLINK spec/expression, this, `this` parameter) which is a reference
2137+
to the struct instance.
2138+
However, an instance method can still be called on an rvalue struct instance,
2139+
even if the method is not const:)
2140+
2141+
$(SPEC_RUNNABLE_EXAMPLE_COMPILE
2142+
---
2143+
struct S
2144+
{
2145+
int i;
2146+
int f() => ++i;
2147+
}
2148+
2149+
void main()
2150+
{
2151+
//S().i++; // cannot modify, `S().i` is not an lvalue
2152+
assert(S().f() == 1); // OK
2153+
}
2154+
---
2155+
)
2156+
2157+
$(RATIONALE An instance method may have other side effects besides mutating a field,
2158+
or it may produce a useful return value. In the general case, throwing
2159+
away changes to a field after the method returns does not necessarily indicate
2160+
a logic error.)
2161+
2162+
21302163
$(H2 $(LEGACY_LNAME2 StructDestructor, struct-destructor, Struct Destructors))
21312164

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

0 commit comments

Comments
 (0)