简体   繁体   中英

Java and C++ on Stack Unwinding issue

As far as I know, in case of an uncaught exception, C++ destroys the local variables immediately, Java releases the references and leaves the rest for the garbage collector.

Is this right? What exactly is the difference between Java and C++ on this issue? in other words, which of these two languages is considered better in terms of stack unwinding issue? :)

I'm going to get flamed for this but...

C++ is hands down better than Java on the stack unwinding front--there's just no contest. C++ object destructors fire all the way back up the stack until the catch point is reached--releasing all managed resources gracefully along the way.

As you said, Java leaves all of this at the mercy of the non-deterministic garbage collector (worst case) or in the hands of whatever explicitly crafted finally blocks you've littered your code with (since Java doesn't support true RAII). That is, all the resource management code is in the hands of the clients of each class, rather than in the hands of the class designer where it should be.

That said, in C++, the stack unwinding mechanism only functions properly if you're careful to ensure that destructors themselves do not emit exceptions. Once you've got two active exceptions, your program abort() 's without passing go (and of course without firing any of the remaining destructors).

Stack unwinding is specifically calling destructors of all fully constructed objects up the call chain up to the point where the exception is caught.

Java simply has no stack unwinding - it doesn't do anything to objects if an exception is thrown. You have to handle the objects yourself in catch and finally blocks. This is mainly why C# introduced using statements - they simplify calling IDisposable.Dispose(), but again that's not the complete replacement for C++ stack unwinding.

你是完全正确的,C ++以相反的顺序销毁所有局部变量,因为它退出堆栈上的每个函数 - 就像你以编程方式执行return - 而不是main()

For the stack do both the same: They release the stack for the blocks that you leave with the exception. In Java all primitive types (int, double etc.) are saved directly, local variables of this type are released in this moment. All objects are saved through references in local variables, so the references are removed, but the objects itself stay on the heap. If this was the last reference to the object, they are released on the next garbage collection. If in C++ are objects created on the heap and the local variables keep a pointer, the objects on the heap aren't released automatically, they stay on the heap forever (yes, you get a MEMORY LEAK). If you have saved objects on the stack, then the destructor is called (and may release other referenced objects on the heap).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM