There seems to be a major problem with handles pointing to "this" that are created in constructors that do not succeed.
I have two classes A and B. B needs to store an A handle (since A is a kind of parent). This handle is passed as an argument of the B constructor. Class A creates instances of B in its own constructor. But the constructor of A might fail, which results in throwing an exception.
This seems to be a standard situation to me. I have checked the web and throwing exceptions from constructors is considered "good programming", since a constructor has no return value and by throwing an exception it can signal, that something went wrong during construction.
But now there is a real problem. Please check the following pseudo code.
// Create handle that can be passed during the creation of B.
Handle(A) thisHandle = this;
// Here let the constructor fail.
// Create B.
When a constructor throws an exception, the construction was not finished and the destructor must not be called. But when thisHandle goes out of scope, it deletes this, which leads to a segmentation fault. If there was a way to prevent handles from deleting their stored pointer ("deactivate" the handle), I could catch the exception in the constructor of A, deactivate the handle and then rethrow the exception. But as far as I know there is no way to achieve that.
Has anyone experience with such problems? Have I made wrong design decisions?
To explain my design intentions: if creation of A succeeds, the caller of the A constructor would get the A handle and then both the construction context of A and B would store the same handle to A.
Thank you very much for any hint!