c++ - Why is there a memory leak when an exception is thrown from a constructor? -


i read book c++ how program 8th edition paul deitel. there statement @ p.645:

when exception thrown constructor object that's created in new expression, dynamically allocated memory object released.

to verify statement, wrote code follows:

#include <iostream> #include <exception> #include <memory>  class a{ public:   a(){std::cout << "a coming." << std::endl;}   ~a(){std::cout << "a leaving." << std::endl;} }; class b { public:   b()   {     std::cout << "b coming." << std::endl;     b;     throw 3;   }   ~b(){std::cout << "b leaving." << std::endl;} };  int main(void) {     try     {         std::shared_ptr<b> pi(new b);     }     catch(...)     {       std::cout << "exception handled!" << std::endl;     } } 

the output is:

b coming. coming. leaving. exception handled! 

this shows b's destructor isn't invoked, seems conflict statement above.

is code correct verify statement? if not, how should modify it? if yes, mean statement wrong?

it means in ctor of b point of exception destruction. instance of b never constructed, therefore must not destructed. note pi never constructed.

std::shared_ptr<b> pi(new b)  - start new b new b                         - triggers ctor of b std::cout ...                 - output  b;                          - construct throw 3;                      - calls ~a()                               - rewind, new b "aborted"                               - std::shared_ptr<b> pi(new b) "aborted" 

you modify code see, constructor of std::shared_ptr never hit replacing new class of yours, taking pointer:

struct t {   t(b*) { std::cout << "t::t()\n"; } }; ... try {     t pi(new b);  // instead of std::shared_ptr<b> pi(new b); } ... 

the constructor of t not hit (cf. "pi never constructed").

now assume constructor of b allocate memory in:

b() {   a* = new a();   // in contrast a;   throw 3; } 

were a::~a() called, deconstructed, have pointer, , pointers don't need deconstructed. memory allocated , assigned not deleted. (had used smart pointer std::unique_ptr<a> = std::make_unique<a>();, memory have been released, because destructor of std::unique_ptr<a> called , release memory.)


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -