June 05, 2022
On 6/5/22 14:57, Ali Çehreli wrote:

> struct Foo {
>    Foo dup() {
>      auto result = Foo(this.payload);
>      // ...
>      return result;
>    }
> }
>
> In that case, the "named return value optimization" (NRVO) would be
> applied and the object would still be moved to 'x'.

I am wrong there as well: Technically, NRVO (or RVO) does not move but constructs the object in the caller's stack frame.

So, if the caller has the following code:

  auto z = existing.dup();

Then 'result' inside dup() is the same as caller's 'z'. Not 'result' but 'z' would be constructed in dup(). No move is performed and no value is actually returned.

Ali

June 06, 2022

On Sunday, 5 June 2022 at 15:45:17 UTC, Salih Dincer wrote:

>

Also, when we write to the screen with writeln(), why four times copy-constructors are running?

Playground: https://run.dlang.io/is/qHvLJe

I solved the problem by implementing the toString() member function. I also had to use a helper writeout() as below:

struct Foo {

  string toString() {
     return format("%s", payload);
  }

void main() {

  void writeout(T)(T text) {
    text.toString.writeln;/*
    import std.conv;
    text.to!string.writeln;//*/
  }
  writeout(three);

Interestingly, even using to!string the copy-constructor works extra +4 times! I think there will be performance losses if write() is used unconsciously everywhere! Although this way, it kisses with ctor +1 times :)

SDB@79

1 2
Next ›   Last »