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

Any differnece between value types and reference types for =sink ? #23626

Closed
zbzpo2002 opened this issue May 19, 2024 · 1 comment
Closed

Any differnece between value types and reference types for =sink ? #23626

zbzpo2002 opened this issue May 19, 2024 · 1 comment

Comments

@zbzpo2002
Copy link

Description

import strutils
type 
    Person = object
       name: string
       age: int       
    Personobj = ref Person

proc `=destroy`(x: var Person) =
    var address = cast[int](addr x).toHex
    echo x.name & " with address " & address & " object was destroyed!"    

proc `=sink`(dest: var Person; source: Person) =
   echo "sink starts"
   `=destroy`(dest)
   wasMoved(dest)   
   echo "sink ends"

proc `=copy`(dest: var Person; source: Person){.error.} =
    echo "copy hook"
    if dest.name != source.name :
       dest.name = source.name
       dest.age = source.age
    echo "copy hook end"

proc `=wasMoved`(x: var Person) =    
    x.name = "empty111"
    x.age = 0

proc main() =   
    let a1  = Person(name:"a1", age: 20)  
    var a2  = Person(name:"a2", age: 21)        
    var a1address = cast[int](addr a1).toHex   
    var a2address = cast[int](addr a2).toHex
    echo "a1.address = " & a1address
    echo "a2.address = " & a2address      
    a2 = a1
    echo "program end====="
main()

For a value type, Nim compier will call destructor twice, I wonder whether it's designed behaviour ? if yes, why ref object calls =destry once ?

Nim Version

Nim Compiler Version 2.1.1 [Windows: amd64]
Compiled at 2024-05-18
Copyright (c) 2006-2024 by Andreas Rumpf

active boot switches: -d:release

Current Output

a1.address = 000000DE975FF590
a2.address = 000000DE975FF570
sink starts
a2 with address 000000DE975FF570 object was destroyed!
sink ends
program end=====
 with address 000000DE975FF570 object was destroyed!
empty111 with address 000000DE975FF590 object was destroyed!

Expected Output

a1.address = 000000DE975FF590
a2.address = 000000DE975FF570
sink starts
a2 with address 000000DE975FF570 object was destroyed!
sink ends
program end=====
empty111 with address 000000DE975FF590 object was destroyed!

Possible Solution

n/a

Additional Information

n/a

@Araq
Copy link
Member

Araq commented May 20, 2024

No bug here, you need to check for the "wasMoved" state inside your destructor. The manual is pretty clear about this.

@Araq Araq closed this as completed May 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants