1) never use: using namespace std; https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice 2) desctructor is called, but to test this it's better to use try-catch: https://godbolt.org/z/M6zq6Wzov
It depends on the ABI. The C++ standard guarantees that destructors will be run when the stack is unwound. But in this case, the stack is not unwound. Exception handling in x86_64 happens in two stages. In the first stage, a personality routine is run to check where the matching catch handler is found. In the second stage the stack is unwound till the function where the catch handler is located and the destructor is run for all local objects in the stack frames that were destroyed. In your case, no catch handler is found and hence it is not guaranteed that destructors will be run. It is also entirely possible for an ABI to define that destructors will be run in such cases. The C++ standard does not guarantee this but. It depends entirely on the ABI.
So do I need to clear() my objects before throwing the exception? However I think this is not really an effective way. For example, what about allocated data for other objects ? They won't be freed up
What is the use of throwing an exception if you won't catch it anywhere? The process will be terminated anyway
So just using a try/catch will be fine ?
Yes having a catch block somewhere that can handle the exception will ensure that destructors in the wound up stacks are run. I however think that you don't understand exceptions completely yet. I would suggest reading Herb Sutter's guide to exception handling to understand it before using it in your code. It cant be explained easily here.
If you throw an exception try to catch it (otherwise there'll most probably be a crash). If you catch your exception, the dtor is called. You could also try and test it.
Yeah, I would like the program to crash. That's my preference. For example when the user attempts to access a block of memory that doesn't exist (which is seg fault)
If a SEGFAULT occurs, why would you need to even bother about exceptions? The OS would signal your process in this case. Like I said earlier, please read more about exceptions and also the use cases where they would be relevant.
Oh ok. I thought I should care about any possible misuse of my program
I don't know of any case in which crashing is considered fine. You could handle the exception, let the user know of their mistake and then terminate the program. That's much better.
Обсуждают сегодня