According to valgrind
the following code does not contain memory leaks:
#include <memory>
#include <stdexcept>
namespace {
class Foo {
public:
Foo();
};
Foo::Foo() { throw std::runtime_error("This is an error"); }
} // anonymous namespace
int main(int argc, char* argv[]) {
try {
new Foo();
} catch (const std::exception& aError) {
return -1;
}
return 0;
}
Indeed. the result of valgrind --leak-check=full
is:
==25913== Memcheck, a memory error detector
==25913== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==25913== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==25913== Command: ./test
==25913==
==25913==
==25913== HEAP SUMMARY:
==25913== in use at exit: 0 bytes in 0 blocks
==25913== total heap usage: 4 allocs, 4 frees, 72,890 bytes allocated
==25913==
==25913== All heap blocks were freed -- no leaks are possible
==25913==
==25913== For counts of detected and suppressed errors, rerun with: -v
==25913== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
The program is compiled with g++ (GCC) 7.3.0
.
Note: there is no leak even with clang 5.0.1
.
Note: I checked the disassembly code and there is delete
call.
My question: why this code does not produce memory leak? Is it really something specified in the standard (can you link?) or just autonomous compiler enhancement?
What I expect:
...
call operator new(unsigned long)
mov rbx, rax
mov rdi, rbx
call (anonymous namespace)::Foo::Foo()
The dynamic allocation happens, after the call to the constructor which throws producing leak.