Search code examples
c++windowsexceptionundefined-behaviorscoping

Try catch scoping of class variable initialisation


I'm having difficulties trying to find a solution that will allow me to keep the scope of an object local to a main method while catching a potential initialisation exception.

The pseudocode below tries to best illustrate my problem.

int main () {
    // Initialisation
    SomeObject * object;

    try {
         SomeObject obj; // Initialisation can cause an exception
         object = &obj;
    }
    catch (SomeException &ex) {
         // Handle exception
    }

    // object out of scope undefined behaviour

    // Application Logic
    return 0;
}

I understand that the object will be deleted once the try block ends and so the pointer when used will lead to undefined behaviour.

How can I do something like this and pass the object to the function scope so the object is not deleted?

I can use a c++14 solution in my project.


Solution

  • How can I do something like this and pass the object to the function scope so the object is not deleted?

    You can use a smart pointer instead:

    int main () {
        // Initialisation
        std::unique_ptr<SomeObject> object;
    
        try {
             object = std::make_unique<SomeObject>(); // Initialisation can cause an exception
        }
        catch (SomeException &ex) {
             // Handle exception
        }
    
        if(object) {
            // Application Logic
        }
        return 0;
    }