⬆️ ⬇️

What is so difficult about handling C ++ exceptions?

image

Exceptions and the associated stack promotion is one of the most enjoyable techniques in C ++. Exception handling is intuitively consistent with the block structure of the program. Externally, exception handling seems very logical and natural.



Careful use of stack objects allows you to create very efficient and safe code, where, unlike systems with garbage collection, reference locality is preserved, which makes it possible to reduce the number of calls to the system behind the memory, reduce its fragmentation, more efficiently use the cache memory.



However, in C ++, exceptions are traditionally considered literally as exceptions to error recovery. It is difficult to say whether this is a cause or a consequence of the fact that the implementation of exception handling by compilers is extremely expensive. Let's try to figure out why.

')

Continued here .

How are things.



There are two approaches to implementing exception handling:



A few examples:

Details can be found here , here and here .



What if ...

And, it would seem, all that matters is to call in the right order destructors whose bodies already exist. How did it happen that a simple, in general, problem has such viscous, heavy and, moreover, independently developed solutions? It is difficult to say, it happened so historically.

Let's try to sketch a solution, trying to keep it simple and, whenever possible, architecturally independent.



Restrictions

This solution has many disadvantages:



But still.

Despite the described limitations, the described method has inherent advantages:

Is it possible to eliminate the disadvantages of this method, while retaining its advantages? Yes and no. Using only C ++ tools, it is impossible to do this.



What the author tends.

In the order of technical nonsense, we will think about how to modify the compiler in order to correctly implement the above scheme?

What was missing from the above solution? Knowledge of how the object was spawned.

For example, if an object is built on memory allocated from a common heap and can migrate between threads, it can in no case be registered in a thread-dependent stack. It is not necessary to register an object aggregated into another object anywhere.

And with an object of the same type, but on a stack memory, it is necessary to do this. Of course, it is possible to give a pointer to this stack object to another thread, but it is difficult to imagine in what situation this could be useful.

So:





By the way.





PS: Special thanks to Alexander Artyushin for informative discussion.

Source: https://habr.com/ru/post/208006/



All Articles