Pergunta

The basics of reference counting for allocated struct 'objects' seem pretty straightforward to me: Give new objects a RC of 1; On assignment decrement the RC (and free if RC=0) of the old object and increment the RC of the assigned object; Decrement the RC of all objects leaving scope.

However i'm a bit puzzled about what i need to do when RC'ed objects are passed to / returned from functions. Do i have to inc/dec the RC before/after each function call and where should the inc's and dec's be put if they are necessary (at the start & end inside the function or before & after the function call?)? What about RC'ed objects returned by a function?

Foi útil?

Solução

Generally speaking, any time a new reference is created, you'd increment, and every time one is destroyed/discarded, you'd decrement.

Function arguments require a copy, so that's an increment. A function return value requires a copy, so that's an increment. Of course, in many cases, there'll be corresponding, simultaneous discards as well, so you could potentially optimise by not modifying the count.

Of course, in C, this can get very complicated and error-prone very quickly, because you have to do everything manually. A broken/unreliable reference-count mechanism is arguably worse than none at all.

Outras dicas

Incrementing a reference count is a it like saying "I'm interested in what the points to, so I've stored the pointer somewhere. Please don't free it while I'm not looking".

As such every time you store the pointer is a 'reference' and must be counted.

If the function does not store the pointer somewhere, you shouldn't need to increment it. If you store the pointer, once you are done with using it, decrement the reference count.\

Quite often, an 'object' will be returned with a reference count already set to 1. You will have to read that functions documentation to know whether it has 'passed ownership' of the reference to you (in which case you will have to decrement the count), or if there is some other function you need to call that will decrement it and remove references to that pointer internal to the other object.

I think function is the same.
If you passed a pointer to a function call, why don't you treat it as an assignment?(so I think the RC should be incremented)
When you leave the function, I think it's same as leaving the scope.
About the return value, if it's used for an assignment, then as you said, RC + 1, or RC doesn't need to change.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top