Note that there are some explanatory texts on larger screens.

plurals
  1. POdestructor not called in case of exception with scoped_ptr
    text
    copied!<p>I have just started using c++ boost libraries. I read in many places that when a scoped_ptr is used then the object is always destroyed even in case of exceptions.</p> <blockquote> <p><a href="http://www.boost.org/libs/smart_ptr/" rel="nofollow">They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects.</a> </p> </blockquote> <p>I tried in the following code.</p> <pre><code>#include&lt;boost/scoped_ptr.hpp&gt; class B { public: B(){ std::cout&lt;&lt; "B constructor call\n"; } ~B(){ std::cout&lt;&lt;"B destructor call\n"; } }; class A { public: boost::scoped_ptr&lt;B&gt; b; A():b(new B()) { throw 1; } }; int main() { A a; return 0; } output: B constructor call terminate called after throwing an instance of 'int' Aborted (core dumped) </code></pre> <p>There is no call to B's destructor. But I used scoped_ptr so it should have called B's destructor or did I mis-interpreted the use of scoped_ptr. </p> <p>But if a surround it with try catch then B's destructor is called.</p> <pre><code>try{ A a; } catch( ... ) { } </code></pre> <p>In this case destructor of A will be called as all locally allocated objects in case of exception in a try block are removed from the stack and I have my pointer wrapped inside and object of scoped_ptr so when the destructor of scoped object destroys which ultimately the pointer. So is scoped_ptr is useful because we don't have to explicitly delete the memory allocated or I mis-interpreted the description of scoped_ptr. </p> <p>How can I call the destructor of class B in case of exception using scoped_ptr </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload