Skip to content

memory leak due to non-destructed object #124306

@mrussoLuxoft

Description

@mrussoLuxoft

This web page:

cppquiz

shows an error of Clang about destruction order in case of exception while destructing local objects after having constructed the returned object.

It seems no one reported yet to Clang, is it ?

The code recalls an example from the standard, in [except.ctor]-p2 .

I have elaborated a bit more with some std::cout and some few additional stuff, here: godbolt

Original code is:

struct A { };

struct Y { ~Y() noexcept(false) { throw 0; } };

A f() {
  try {
    A a;
    Y y;
    A b;
    return {};      // #1
  } catch (...) {
  }
  return {};        // #2
}

and the problem is that after the exception throw by y-destruction, the returned object constructed in #1 is not destroyed, also determining a memory leak as shown on godbolt link.

My code elaboration is:

#include <iostream>
#include <stdexcept>

unsigned d = 0;
struct A {
    A(char c) : c_(c), p(new int()) {std::cout << "constr. " << c_ << '\n';}
    ~A() { std::cout << "destr. " << c_ << '\n'; delete p;}
    char c_;
    int *p;
};

struct Y { ~Y() noexcept(false) { throw std::runtime_error(""); } };

A f() {
    try {
        A a('a');
        Y y;
        A b('b');
        return {'c'};
    } catch (...) {
    }
    return {'d'};
}

int main()
{
    A x = f();
}

I also thank Vincenzo Simone to have shared that quiz link and the fact that compilers fail.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions