3

When searching for an answer, I found this question, however there is no mention of static lifetime objects. Can the method mentioned in this answer (calling drop() on the object) be used for static lifetime objects?

I was imagining a situation like a linked list. You need to keep nodes of the list around for (potentially) the entire lifetime of the program, however you also may remove items from the list. It seems wasteful to leave them in memory for the entire execution of the program.

Thanks!

Slothie
  • 61
  • 9
  • Why would you _want_ to drop something with a static lifetime? – jhpratt Sep 27 '19 at 21:37
  • I was imagining a situation like a linked list. You need to keep nodes of the list around for potentially the entire lifetime of the program, however you also may remove items from the list. It seems wasteful to leave them in memory for the entire execution of the program. I can edit the original question to make this more clear. – Slothie Sep 27 '19 at 21:40
  • 1
    @Slothie If you don't want to keep them in memory for the entire execution time, they're not `static` any more. – Bergi Sep 27 '19 at 21:45
  • @Slothie You can use lifetimes on the object, which could be `'static`, but isn't necessarily. – jhpratt Sep 27 '19 at 23:56
  • @jhpratt, can you clarify what you mean by "but isn't necessarily"? – Slothie Sep 28 '19 at 13:43
  • You could still create a `LinkedList<'a>` — `'a` doesn't have to be `'static`. – jhpratt Sep 28 '19 at 17:02
  • I met the same problem. I have a global static `TcpStream` client, and want to impl `Drop` trait for it, to shutdown its sockets when program exits. Since drop a static is not possible, I use `libc::atexit` for cleanup. – Forsworn Apr 13 '23 at 03:12

1 Answers1

5

No. The very point of a static is that it's static: It has a fixed address in memory and can't be moved from there. As a consequence, everybody is free to have a reference to that object, because it's guaranteed to be there as long as the program is executing. That's why you only get to use a static in the form of a &'static-reference and can never claim ownership.

Besides, doing this for the purpose of memory conservation is pointless: The object is baked into the executable and mapped to memory on access. All that could happen is for the OS to relinquish the memory mapping. Yet, since the memory is never allocated from the heap in the first place, there is no saving to be had.

The only thing you could do is to replace the object using unsafe mutable access. This is both dangerous (because the compiler is free to assume that the object does not in fact change) and pointless, due to the fact that the memory can't be freed, as it's part of the executable's memory mapping.

user2722968
  • 13,636
  • 2
  • 46
  • 67
  • This isn’t correct when using `Box::leak()` on a boxed value, which takes a `Box` and pulls it into a `&’static mut`. Creating these in a loop will lead to a memory leak. – zshift Nov 15 '21 at 19:01