Observable behavior and undefined behavior — What happens if I don’t call a destructor?

I simply do not understand what “depends on the side effects” means.

It means that it depends on something the destructor is doing. In your example, modifying *p or not modifying it. You have that dependency in your code, as the output would differ if the dctor wouldn’t get called.

In your current code, the number that is printed, might not be the same number that would have returned by the second rand() call. Your program invokes undefined behavior, but it’s just that UB here has no ill effect.

If you wouldn’t print the value (or otherwise read it), then there wouldn’t be any dependency on the side effects of the dcor, and thus no UB.

So:

Is forgetting to call a destructor any different than forgetting to call an ordinary function with the same body?

Nope, it’s not any different in this regard. If you depend on it being called, you must make sure it’s called, otherwise your dependency is not satisfied.

Furthermore, at what point is it correct to say the program “depends” on the destructor? Does it do so if the value was random — or in general, if there is no way for me to distinguish the destructor from running vs. not running?

Random or not doesn’t matter, because the code depends on the variable being written to. Just because it’s difficult to predict what the new value is doesn’t mean there’s no dependency.

What if I never read the value?

Then there’s no UB, as the code has no dependency on the variable after it was written to.

Under which condition(s), if any, does this program exhibit Undefined Behavior?

There are no conditions. It’s always UB.

Exactly which expression(s) or statement(s) cause this, and why?

The expression:

printf("%d", x);

because it introduces the dependency on the affected variable.

Leave a Comment