# Finalizer only works with mutable structs?

**URL:** https://discourse.julialang.org/t/finalizer-only-works-with-mutable-structs/28777
**Category:** General Usage
**Created:** [September 15, 2019, 1:47am UTC](https://discourse.julialang.org/t/finalizer-only-works-with-mutable-structs/28777 "2019-09-15T01:47:50Z")
**Posts on this page:** 1
**Showing post:** 9

<div class="post-metadata">

### Author: ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)
#### Post date: [September 15, 2019, 11:06am UTC](https://discourse.julialang.org/t/finalizer-only-works-with-mutable-structs/28777/9 "2019-09-15T11:06:23Z")

</div>

> [@tk3369](#):
>
> I thought all objects have a lifetime – it can be collected by the garbage collector when it’s no longer being referenced. Is that not true?

That’s not true. All **ALLOCATIONS** have a lifetime. That allocation may or may not have anthing to do with the object. It might not happen at the same time the object is created in the code (it may not even happen) and may or may not end at the same time as the object. This is especially true for immutables and could also be true for mutables.

> [@leethargo](#):
>
> I want to to use `pointer_to_objref` with an object (because this is passed through a callback function of a C library).

Pass the object using `Any` or a correct `Ref` argument type directly. You almost never want to call `pointer_to_objref` yourself. (If you are calling it, you are likely doing it wrong for mutable types as well)

> [@oxinabox](#):
>
> One option is to add a mutable field, e,g a `Ref` , or a pointer `Ptr` then attach the finalizer to that.

Depending on what you mean here.

1. `Ptr` isnt mutable and `Ref` is an abstract type (neither mutable or immutable).
2. If you mean that adding finalizer to a field of an object for tracking the lifetime of the parent object, then it won’t work. If you make sure that the thing you finalize is limited to that mutable field though it’ll of course work.

---

_[View the full topic](https://discourse.julialang.org/t/finalizer-only-works-with-mutable-structs/28777)._
