In the following code:
#include <memory>
#include <iostream>
void mydeallocator(int * x) {
std::cerr << "Freeing memory" << std::endl;
delete x;
}
struct Foo {
std::unique_ptr <int,std::function <void(int*)>> x;
Foo(bool fail) : x(new int(1),mydeallocator) {
if(fail)
throw;
}
};
int main() {
{auto foo1 = Foo(false);}
{auto foo2 = Foo(true);}
}
It appears that memory is not being deallocated properly when Foo(true) is called. Namely, when we compile and run this program, we have the result:
Freeing memory
terminate called without an active exception
Aborted
I believe that the message Freeing memory should be called twice. Basically, according to this question, my understanding is that the stack should unwind on the constructor for Foo and that x should call its destructor, which should call mydeallocator. Certainly, this is not happening, so why is the memory not being freed?
Aucun commentaire:
Enregistrer un commentaire