Sobes.tech
Junior — Senior

Delete behavior when an exception occurs in the object constructor

livecode

Task condition

How will the program behave if the constructor throws an exception? Will the delete operator be executed and will there be a memory leak?

#include <iostream>

struct Data {
    Data() {
        throw std::runtime_error("exception");
    }
};

int main(int argc, char** argv) {
    try {
        Data* ptr = new Data;
        delete ptr;
    } catch (const std::exception& e) {}
    
    return EXIT_SUCCESS;
}