Questions tagged [reference-counting]
Reference counting is a mechanism whereby a computer language keeps track of when you create and then no longer need an object or data structure, in order to free unneeded memory. Traditionally this would have been done manually by the programmer.
454
questions
1
vote
1
answer
47
views
Why does getrefcount increase by 2 when put inside a function?
Consider the following code.
import sys
a = [1, 2, 3]
def foo(x):
print(sys.getrefcount(x))
foo(a) # prints out 4 -- but why?
When we invoke foo(a) and when print(sys.getrefcount(x)) executes, ...
3
votes
2
answers
123
views
Comparing 2 method of C++ ref-counting
To write a ref-counted class, I have seen 2 different approaches:
Approach 1:
struct RefCounting1 {
void ref_up() {
m_ref.fetch_add(1, std::memory_order_relaxed);
}
void release() {
if (...
0
votes
1
answer
31
views
Design pattern for constructing resource at first thread arrival and destructing on last thread departure
I'm looking for a concurrency design pattern in C++ which enables a single resource instance to be constructed by the first thread which needs it, persist as long as at least one thread is accessing ...
-2
votes
1
answer
97
views
Why does cloning an Rc pointer in Rust increase its strong_count?
I have this function:
use std::rc::Rc;
fn rc_counter() -> Rc<String> {
let p1 = Rc::new(String::from("Hello"));
println!("count {}", Rc::strong_count(&p1)); //...
0
votes
0
answers
42
views
How to reuse the underlying vectors in a struct of arrays
I come from C# where a common technique to reduce the overall memory footprint and improve efficiency was to recycle the underlying arrays in an immutable struct of arrays. In the below example, the ...
0
votes
1
answer
87
views
When using a ThreadPool passing Arc with reference gives a "data escapes the function body" error, passing Arc of data itself works fine
I've written some code to break up independent chunks of a computation into pieces and then feed each of the pieces to a thread pool which then does the computation and passes the result back the main ...
0
votes
0
answers
110
views
Using weak references with structs with lifetime parameters
I want to implement the observer pattern using Weak smart pointers. Ideally this would look something like the following (playground):
use std::cell::RefCell;
use std::rc::{Rc, Weak};
struct ...
1
vote
1
answer
29
views
Rust vector of struct instances with (non-circular) references to each other
I'd like to create a vector of TestStruct. TestStruct has an optional reference to another TestStruct instance. No TestStruct will ever reference itself, nor will there be circular references with the ...
0
votes
1
answer
117
views
Which memory management techniques exist?
I know of these three techniques:
Manually
uses
System.Classes;
procedure DoSomething;
var
sl: TStringList;
begin
sl := TStringList.Create;
try
finally
sl.Free; // Invoking destructor
...
0
votes
1
answer
86
views
How to do COM dll reference counting the right way? Official Microsoft samples are inconsistent
Some implementations calls DllAddRef() and DllRelease() in the CClassFactory constructor, destructor, and LockeServer member function:
https://github.com/microsoft/workbooks/blob/master/Clients/...
0
votes
1
answer
46
views
Peekable content is None after refactor the code
I have this method:
fn parse_http_request_headers<'b>(sp: &'b mut std::str::Split<&str>) -> HashMap<String, String> {
let mut headers: HashMap<String, String>...
1
vote
1
answer
118
views
how to count all pointers and variables that using an dynamically allocated memory with malloc and new?
if we override malloc and new function we can track first created pointer . but how can i track and count other pointers and functions that using this allocated memory ? (q pointer in below code ) ...
0
votes
1
answer
50
views
Does dereferencing a GArray unref it?
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
#include <glib.h>
void transform_pointer_contents(GArray* const arr) {
GArray* const tmp = g_array_new(true, ...
0
votes
1
answer
174
views
Thread-safety of reference count in std::shared_ptr
Looking at this implementation of std::shared_ptr https://thecandcppclub.com/deepeshmenon/chapter-10-shared-pointers-and-atomics-in-c-an-introduction/781/ :
Question 1 : I can see that we're using std:...
0
votes
1
answer
111
views
Details of PHP 7.4 Reference Counting of Zvals
I have some points of clarification based on reading the internal implementations for zvals described here Internal value representation in PHP 7 - Part 1 and Internal value representation in PHP 7 - ...
0
votes
1
answer
57
views
Can python generational garbage collector kick in before objet is released by reference counting
In a CPython multithreaded environment, consider the following code
class Container:
def __del__(self):
# Some code that fails when run in a different thread than the thread that ...
1
vote
2
answers
123
views
Woes with std::shared_ptr<T>.use_counter()
https://en.cppreference.com/w/cpp/memory/shared_ptr/use_count states:
In multithreaded environment, the value returned by use_count is approximate (typical implementations use a memory_order_relaxed ...
4
votes
2
answers
169
views
Why does creating a variable name for an exception raised in a Python function affect the reference count of an input variable to that function?
I've defined two simple Python functions that take a single argument, raise an exception, and handle the raised exception. One function uses a variable to refer to the exception before raising/...
1
vote
1
answer
463
views
Rc with zero references
Am I able to create an Rc with zero (strong) references? How to do this?
I am doing references counting digraphs. An empty digraph would be represented as an Rc variable with zero references.
If it is ...
5
votes
2
answers
187
views
Are generators with context managers an anti-pattern?
I'm wondering about code like this:
def all_lines(filename):
with open(filename) as infile:
yield from infile
The point of a context manager is to have explicit control over the lifetime ...
0
votes
2
answers
133
views
Do we need to use root = None during in the function? (python BST, reference counting)
I am practicing deleting node in BST and came across the following code.
def deleteNode(root, key):
if root is None:
return root
if key < root.key:
root.left = deleteNode(...
2
votes
1
answer
57
views
Why are references to python values, that are function parameters, stored on the stack(frame) in CPython?
Python works with reference counting. That means, if there is no more reference to a value, then the memory of that value is recycled. Or in other words. As long as there is at least one remaining ...
2
votes
3
answers
724
views
When is the reference count for a local variable in a python function decreased?
I have the following function:
def myfn():
big_obj = BigObj()
result = consume(big_obj)
return result
When is the reference count for the value of BigObj() increased / decreased:
Is it:
...
2
votes
1
answer
125
views
How to share resources without exposing Rc in the API?
I'm working on a geometry crate and I thought in order for things to work nicely I should use Rc when referencing shared points. For example:
struct Point {
point: Vec4,
}
struct Line {
...
2
votes
0
answers
40
views
Reference counting in python [duplicate]
I am learning how reference counting works in python and I am confused.
def get_full_list ():
a = object ()
b = object ()
c = object ()
l = [a, b, c]
return l
l = get_full_list ()
...
13
votes
2
answers
926
views
When is reference-counting needed in a single threaded application that doesn't model circular data structures?
Rust can handle reference counting very elegantly with Rc. It seems many members of the community prefer not to use this and instead use the ownership/borrowing semantics of the language. This results ...
1
vote
2
answers
208
views
Method call after garbage collection is finished
I have a class "Foo" where the objects are registered in an object called FooManager. After the scope of a function is left the Foo objects can only be deleted if I know ALL the Foos which ...
4
votes
1
answer
347
views
Does C++ offer a thread-safe reference counter?
Is there a thread-safe reference counter class in the standard C++ library, (or as an extension in Visual Studio), or would I need to write this kind of object from scratch?
I'm hoping for an object ...
2
votes
2
answers
611
views
Swift: keeping a strong reference to a weak variable
I have a class with a weak reference to its delegate. In a background operation, I need to set the delegate, perform an operation on the class, and then have the delegate released.
The code below ...
-1
votes
1
answer
143
views
Increment reference count of Python object
I have a static method that returns a new instance of it's class. The problem is that the instance is None in the code that called the method. I believe this is due to the fact the instance is ...
1
vote
0
answers
192
views
How to find and read an output from get_referrers an why its lenght is different from getrefcount in python
I'm trying to debug my software and find every reference to an object, so I can fully delete it .
So when I did:
gc.collect()
print('it has '+str(sys.getrefcount(my_obj))+' references')
...
1
vote
1
answer
564
views
Understanding reference count in python
I'm trying to understand how reference count work in python. I created a variable x and assigned a value of 10 to it. So basically x is pointing to the memory location where object of class int (10) ...
0
votes
2
answers
2k
views
Argument requires that value is borrowed for `'static` not working for non copy value
The below code doesn't work because the argument to thread::spawn requires that some is borrowed for 'static, I get it:
fn main() {
let some = "Some".to_string();
let apple = Arc::...
0
votes
0
answers
127
views
How are atomic reference counts propagated to all copies of all class?
I try to understand how atomic reference counting works but fail to grasp how reference counts propagate to all copies of an instance. Based on this question and on the boost reference I constructed ...
0
votes
2
answers
133
views
What is the best practice of passing reference counted C++ objects to Lua?
I want to have my reference counted C++ object also managed in Lua callbacks: when it is held by a Lua variable, increase its refcount; and when the Lua variable is destroyed, release one refcount. It ...
1
vote
1
answer
371
views
How do I implement an iterator from a vector of std::Rc<std::RefCell<T>> smart pointers?
I'm trying to understand how to work with interior mutability. This question is strongly related to my previous question.
I have a generic struct Port<T> that owns a Vec<T>. We can "...
3
votes
1
answer
596
views
Rust: implementing an iterator from a vector of std::Rc smart pointers
I'm starting with Rust, and I'm already facing problems with data ownership.
I want to implement a generic struct called Port<T> that has a vector of values Vec<T>. Also, this struct has a ...
4
votes
1
answer
282
views
Why does unwrapping a cloned Rc cause a panic?
Why does this code panic on line 7? Shouldn't foo_unwrapped be Some(3) on line 5 instead of None?
use std::rc::Rc;
fn main()
{
let foo: Rc<i32> = Rc::new(3);
let mut foo_cloned = Rc::...
0
votes
0
answers
56
views
Can this object reference counter be replaced with shared_ptr (or some smart pointer)?
Here's an example program which emulates a "hot potato". The Potato object gets created and can be passed around through copying, moving, etc. and once the Potato finally gets destroyed ...
3
votes
1
answer
520
views
How to share parts of a string with Rc?
I want to create some references to a str with Rc, without cloning str:
fn main() {
let s = Rc::<str>::from("foo");
let t = Rc::clone(&s); // Creating a new pointer to the ...
0
votes
0
answers
58
views
Issues with accessing PyObjects after writing
I am trying to do some fairly simple list manipulation, using a Jupyter notebook that calls a DLL function. I'd like my Jupyter notebook/Python code to pass in a Python list to a C++ function, which ...
6
votes
1
answer
440
views
How does the split reference counting work in a lock free stack?
I am reading C++ concurrency in action 2nd.
It introduces split reference counts for a lock free stack.
One possible technique involves the use of not one but two reference counts for each node: an ...
-3
votes
1
answer
94
views
Actual uses of shared_ptr? [closed]
For me, shared_ptr seems like a lazy solution to memory management, instead of using a well thought zero overhead ownership system ofunique_ptr for owning pointers, raw pointers for observing ...
0
votes
0
answers
100
views
How does reference counting work on a deeply nested, non cyclical object?
Say you have this sort of structure, but imagine it was super deeply nested like 20 levels deep:
function getIt() {
let a = { hello: 'world' }
let b = { foo: 'bar', deeply: { nested: true } }
a....
0
votes
0
answers
68
views
How to upcast an Rc<dyn Foo> [duplicate]
Is it possible to upcast an Rc<dyn Foo>? If not, why not?
use std::rc::Rc;
trait Bar {}
trait Foo: Bar {}
fn upcast(this: Rc<dyn Foo>) -> Rc<dyn Bar> {
this
}
results in
...
4
votes
1
answer
534
views
Reset scoped container in inversifyjs
I'm implementing a scoped container architecture such that a new container is created for every Express request (or apollographql request). I have a lifecycle method that can be called after we're ...
-1
votes
1
answer
74
views
Custom reference counting pointer calls destructor right after creation
I am currently reading the "3D Game Engine Architecture" book by David H. Eberly, and decided to implement my own little reference counting smart pointer. I have mostly followed his ...
2
votes
1
answer
511
views
Why don't these lock-free reference counting implementations explode (or do they)?
I'm trying to wrap my head around LFRC algorithms but I keep finding examples where I assume that they work, but I can't understand why. I'm focused on copying and deletion. There are three in ...
0
votes
0
answers
22
views
Providing specialization for templateed class method with two parameters (one being a non-type)
Background information: I'm on a microcontroller with a preference of pre-allocating as much as possible. We've wrapped the RTOS with C++ objects that are easier to deal with and allow us to have ...
2
votes
3
answers
175
views
How can I get a reference count to an ADODB recordset object?
I'm investigating a memory leak in some old VB6 code that seems to be related to recordset objects, so I'm trying to get the reference counts on the objects. I found some code online that will give a ...