Hacker News .hnnew | past | comments | ask | show | jobs | submitlogin

That's interesting! So i assume that this macro allows code to get registered to be run after the 'current' scope exits.

But from my understanding (or lack thereof), the `auto _defer_instance_1234 =` is never referenced post construction. Why doesn't the compiler immediately detect that this object is unused and thus optimize away the object as soon as possible? Is it always guaranteed that the destructor gets called only after the current scope exits?



> Why doesn't the compiler immediately detect that this object is unused and thus optimize away the object as soon as possible? Is it always guaranteed that the destructor gets called only after the current scope exits?

Yes, exactly. The destructor is allowed to have some visible side effect such as closing a file handle or unlocking a mutex that could violate the assumption of the code in that block. (Even just freeing some memory could be an issue for code in the block.) It is guaranteed that the destructor is closed at the end of the block, and that all the destructors called in that way happen in reverse order to the order of their corresponding constructors.


Yes, this is guaranteed. The compiler cannot simply elide statements with effects.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: