Code in fucntion that is awlays executed.

Hello Forum,

Is it possible to have code in a function that always will be executed? To close a stream or call delete[]? Similar like a deconstructor of a class.

Thank you.
I must be missing something in your question.

If you have no conditionals in your function, all the statements will be executed.

If you have conditionals with early returns, then you must include the code you wanted executed on exit before each return statement.
Hello,

Ok, thank you.

Yes, I mean a piece of code that is executed after any of the return statements, or after an error occurs.
not in a stand alone function. When you hit return, it stops. It may return a value that alerts the user to do something, or it may throw an exception (see exception handling in c++) that the user may choose to do something, but you can't force it.

you can force it with a class / functor. I don't know if these are still popular, but its a class that behaves like a function and could be rigged to call the destructor or something...

you can also wrap the pointer or stream in a microclass that self destructs cleanly when out of scope, and the function can remain as it was...
Last edited on
closed account (E0p9LyTq)
I mean a piece of code that is executed after any of the return statements

Not possible with a regular function.

after an error occurs.

Exception handling. try/catch blocks.

C++ Exception Handling
https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm

http://www.cplusplus.com/doc/tutorial/exceptions/
Last edited on
Ok, clear. Thanks.
Topic archived. No new replies allowed.