Search⌘ K
AI Features

Discussion: A False Start

Understand the behavior of C++ object construction and destruction when exceptions occur in constructors. Learn why only fully initialized members are destroyed automatically and how to manage resources safely using standard library types and encapsulation, enabling you to write more robust and leak-free code.

Run the code

Now, it’s time to execute the code and observe the output.

C++
#include <iostream>
#include <stdexcept>
struct Engine
{
~Engine() { std::cout << "Engine stopped\n"; }
};
struct Machine
{
Machine() { throw std::runtime_error{"Failed to start the machine"}; }
~Machine() { std::cout << "Machine stopped\n"; }
Engine engine_;
};
int main()
{
try
{
Machine machine;
}
catch (...)
{
}
}

Understanding the code

In this puzzle, we have a Machine class that contains an Engine. But Machine throws in its constructor before it’s completely done initializing. Does the engine get stopped? Does the Machine itself get stopped?

Object destruction

One of the great things about C++ is that constructed objects get destroyed automatically and deterministically (unless we manually call new, which these days should be left to library authors). We’ll find no need for Python’s with or C#’s using, and rarely a need for something like finally. ...