In Effective C++ 3/E, I read this:
This is exception unsafe code:
class Test { };
void foo(const std::shared_ptr<Test> &ptr, int i);
int bar();
...
foo(std::shared_ptr<Test>(new Test), bar());
Because compiler can implement like this:
- run
new Test
- call
bar()
<-- ifbar()
throws exception, the object ofTest
allocated bynew Test
cannot be deleted.- call constructor of
std::shared_ptr<Test>
- call
foo()
But in this case, compiler can know there's memory leak. Can't compiler do delete
automatically if exception is thrown?
In addition, compiler does automatically delete
in that case:
Test *p = new Test;
that is implemented like this:
- call
operator new
to allocate memory- call constructor of
Test
. If constructor throws exception, memory is automatically deleted.
Why compiler doesn't do in first case, unlike second case?