Bug 101961 - Missing returned object destructor call after exception throw
Summary: Missing returned object destructor call after exception throw
Status: RESOLVED DUPLICATE of bug 33799
Alias: None
Product: gcc
Classification: Unclassified
Component: c++ (show other bugs)
Version: 12.0
: P3 normal
Target Milestone: ---
Assignee: Not yet assigned to anyone
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2021-08-18 14:34 UTC by M B
Modified: 2022-08-11 22:59 UTC (History)
2 users (show)

See Also:
Host:
Target:
Build:
Known to work:
Known to fail:
Last reconfirmed:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description M B 2021-08-18 14:34:00 UTC
14.3.2 Exception handling:Constructors and destructors:2 (https://eel.is/c++draft/except.ctor#2)
says
"If an exception is thrown during the destruction of temporaries or local variables for a return statement ([stmt.return]), the destructor for the returned object (if any) is also invoked"

And it contains example (https://eel.is/c++draft/except.ctor#example-1) with description
"...the local variable y is destroyed, causing stack unwinding, resulting in the destruction of the returned object, ..."

Trying to recreate this example with following code

#include <iostream>
using namespace std;

struct S{
  int i = 123;
  S(int i) :i(i) {cout<<"S("<<i<<")"<<endl;}
  ~S() {cout<<"~S("<<i<<")"<<endl;}
};

struct T {
  T() {cout<<"T()"<<endl;}
  ~T() noexcept(false) {
    cout<<"~T()"<<endl;
    throw 0;
  }
};

S foo() {
  try {
    T t;
    return {3};
  } catch (...){}
  return {4};
}

int main() {
  foo();
}

Output doesn't have S{3}'s (returned object) destruction line:
T()
S(3)
~T()
S(4)
~S(4)

while should be
T()
S(3)
~T()
~S(3) <-----!
S(4)
~S(4)

Link to godbolt:
https://godbolt.org/z/hP9z5rYKG
Comment 1 Jason Merrill 2022-01-06 14:31:36 UTC
Same issue as comment 15 in 33799, which I am fixing now.

*** This bug has been marked as a duplicate of bug 33799 ***