I have a class that allocates memory and can throw an exception in constructor, e.g.:
class A
{
int *x;
public:
A () { x = new int; throw 0;}
~A () { delete x; }
};
I want to create objects of such class dynamically. How should I do it to prevent memory leaks?
I've tried to do create objects in a try
block and delete in a catch
block, but address-sanitizer have reported SEGV on unknown address
.
int main()
{
A *a;
try { a = new A; }
catch(int) { delete a; } // AddressSanitizer: SEGV on unknown address
}
Without deletion of the object we have (obviously) a memory leak and leak-sanitizer reports that.
int main()
{
A *a;
try { a = new A; }
catch(int) {} // LeakSanitizer: detected memory leaks
}
However without try - catch
both sanitizers are silent. I am wondering is there still a memory leak and, and if so, how to fix it?
int main()
{
A *a;
a = new A; // terminate called after throwing an instance of 'int'
}
UPD: Yes, I know about shared pointers. My question is mostly about the last case (without handling an exception). Why are sanitizers silent? Is it just leak-sanitizer flow or is there really no leak?