threading icon indicating copy to clipboard operation
threading copied to clipboard

There should be implemented a WeakPtr also

Open Q-Master opened this issue 4 years ago • 6 comments

This code will leak because a refers to b and b refers to a and there's no possibility to fix this not using WeakPtr.

import threading/smartptrs

type
  Widget = object
    oth: SharedPtr[Widget]


var a: SharedPtr[Widget] = newSharedPtr(Widget())
var b: SharedPtr[Widget] = newSharedPtr(Widget())
a[].oth = b
b[].oth = a
echo a
echo b

Also this code goes to infinite recursion in echos.

Q-Master avatar Nov 22 '21 14:11 Q-Master

You can use a ptr though for the "weak" pointer.

Araq avatar Nov 22 '21 19:11 Araq

Yes I can, but also I can use ref instead of SmartPtr. Might it be better just implement some sort of "unique" keyword in Nim itself instead of implementing a new batch of pointers copied from C++ and having the same problems which do they have in C++? Orelse you should say "B" when spoken "A" and implement a WeakPtr too.

Q-Master avatar Nov 24 '21 19:11 Q-Master

I don't understand your point. Adding "unique" to Nim's type system would be much more work than a library solution, obviously.

Araq avatar Nov 25 '21 13:11 Araq

The point is that unique keyword in the Nim itself will add possibility to use any Nim supported type, not only pointers and make this library redundant.

Also this lib lacks WeakPtr, which is obviously should be there. WeakPtr is not just pointer, it is a smart pointer too: it has use count, expiration, destructor and assignment ops and could be locked (converted atomically to SharedPtr).

Q-Master avatar Nov 30 '21 21:11 Q-Master

So add a WeakPtr, you don't have to lecture me what it is. My point was that the existing SharedPtr is far from useless as it is now and that many designs work with ptr as the "unowned" pointer type.

Araq avatar Dec 01 '21 07:12 Araq

I'm just talking that adding unique kw to Nim itself will be better than porting some OOP solutions from C++ with all it's bugs and vulnerabilities (e.x. SharedPtr is unsafe in threading) to the language with very limited OOP. Using ptr as unowned pointer is unsafe in this solution because WeakPtr is not a pointer itself and not providing any dot operations to underlying pointer.

Q-Master avatar Dec 01 '21 08:12 Q-Master