Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent =copy if return value is the last use #19057

Open
derekdai opened this issue Oct 27, 2021 · 0 comments
Open

Prevent =copy if return value is the last use #19057

derekdai opened this issue Oct 27, 2021 · 0 comments

Comments

@derekdai
Copy link
Contributor

Related to this forum post.

Example

from strformat import `&`

type X = distinct int

proc `=sink`(p1: var X; p2: X) = echo &"=sink {cast[int](p2)}"
proc `=copy`(p1: var X; p2: X) = echo &"=copy {cast[int](p2)}"
proc `=destroy`(p: var X) = echo &"=destroy {cast[int](p)}"

proc main =
  echo "~~~~~~~~~~"
  block:
    proc byLet(v: int): owned X =
      let x = X(v)
      x
    discard byLet(1)
  echo "~~~~~~~~~~"
  
  block:
    proc byVar(v: int): owned X =
      var x = X(v)
      x
    discard byVar(2)
  echo "~~~~~~~~~~"
  
  block:
    proc byCast(v: int): owned X = cast[X](v)
    discard byCast(3)
  echo "~~~~~~~~~~"
  
  block:
    proc byConv(v: int): owned X = (X)(v)
    discard byConv(4)
  echo "~~~~~~~~~~"
  
  block:
    proc byVarMove(v: int): owned X =
      var x = X(v)
      move(x)
    discard byVarMove(5)
  echo "~~~~~~~~~~"
  
  block:
    proc byVarWasMoved(v: int): owned X =
      var x = X(v)
      result = x
      wasMoved(x)
    discard byVarWasMoved(6)
  echo "~~~~~~~~~~"

main()

Current Output

~~~~~~~~~~
=copy 1
=destroy 0
~~~~~~~~~~
=copy 2
=destroy 0
~~~~~~~~~~
=copy 3
=destroy 0
~~~~~~~~~~
=destroy 4
~~~~~~~~~~
=destroy 0
=destroy 5
~~~~~~~~~~
=copy 6
=destroy 0
~~~~~~~~~~

Expected Output

~~~~~~~~~~
=destroy 0
~~~~~~~~~~
=destroy 0
~~~~~~~~~~
=destroy 0
~~~~~~~~~~
=destroy 4
~~~~~~~~~~
=destroy 0
=destroy 5
~~~~~~~~~~
=destroy 0
~~~~~~~~~~

Possible Solution

Additional Information

Nim Compiler Version 1.6.0 [Linux: amd64]
Compiled at 2021-10-19
Copyright (c) 2006-2021 by Andreas Rumpf

git hash: 727c6378d2464090564dbcd9bc8b9ac648467e38
active boot switches: -d:release
@derekdai derekdai changed the title Reduce calls of =copy for return value Prevent =copy if return value is the last use Oct 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants