How to convert member function to free function?
Andrey Zherikov
andrey.zherikov at gmail.com
Fri Sep 18 19:20:17 UTC 2020
On Friday, 18 September 2020 at 18:20:41 UTC, Andrey Zherikov
wrote:
> How can I rewrite foo() function as a free-function that won't
> cause struct copying?
I found solution:
========
struct S
{
int i = -1;
this(int n) {i=n;writeln(&this," ",i,"
",__PRETTY_FUNCTION__);}
this(ref return scope inout S rhs) inout
{i=rhs.i+1;writeln(&this," ",i," ",__PRETTY_FUNCTION__);}
~this() {writeln(&this," ",i," ",__PRETTY_FUNCTION__);}
ref auto getRef() return
{
writeln(&this," ",i," ",__PRETTY_FUNCTION__);
return this;
}
}
ref auto foo(return ref S s)
{
writeln(&s," ",s.i," ",__PRETTY_FUNCTION__);
return s;
}
void main()
{
S(5).getRef().foo().foo().foo();
}
========
Output confirms that there is no copying happens:
========
7FFDE98BDDF0 5 S onlineapp.S.this(int n) ref
7FFDE98BDDF0 5 onlineapp.S.getRef() ref return
7FFDE98BDDF0 5 onlineapp.foo(return ref S s) ref @system
7FFDE98BDDF0 5 onlineapp.foo(return ref S s) ref @system
7FFDE98BDDF0 5 onlineapp.foo(return ref S s) ref @system
7FFDE98BDDF0 5 void onlineapp.S.~this()
========
More information about the Digitalmars-d-learn
mailing list