Junior — Middle
Will there be a memory leak if an exception is thrown inside a constructor using new?
sobes.tech AI
Answer from AI
If an exception is thrown inside the constructor of an object allocated with new, the memory allocated for that object will be automatically freed, and memory leaks will not occur. This is because the new operator in C++ first allocates memory, then calls the constructor. If the constructor throws an exception, the new operator guarantees the release of the allocated memory.
Example:
struct A {
A() {
throw std::runtime_error("Error in constructor");
}
};
int main() {
try {
A* a = new A(); // If the constructor throws an exception, memory will be freed
} catch (...) {
// Exception handling
}
}
Thus, in this case, a memory leak does not occur.