Why doesn't exit unwind?

It seems a little odd that a safe function will bypass destructors. Is there any reason std::process::exit doesn’t unwind the stack? Personally, I think we need two functions:

fn std::process::exit(code: i32);
unsafe fn std::process:exit_now(code: i32);
2 Likes

It is currently not considered unsafe to leak memory or resources in Rust. For example:

  • You can trivially create a cycle using Rc + RefCell that will leak and never destroy its contents
  • You can exit the main thread while other threads are running, not running their destructors

As a result, not running destructors is not considered unsafe, so this function was introduced as safe

Got it. I always forget that unsafe only refers to memory access, not general behavior.

As a result, not running destructors is not considered unsafe, so this function was introduced as safe.

Just for complete correctness in case anyone comes across this thread later, this isn't always true. Failing to call a destructor before freeing or failing to call a destructor on drop is unsafe. there is no guarantee that a destructor will ever be called.

1 Like

Unsafe or not, the design of this function seems off to me. What’s the reason behind not calling destructors by default?

I see two distinct use cases here:

  1. Choosing a custom error code

  2. Aborting the program without doing any cleanup

The current exit() conflates these two cases, when most of the time you only want the first.

For what it’s worth, the KJ C++ library also encourages RAII style together with a non-unwinding exit(), and its documentation gives some well thought out justification.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.