Note that there are some explanatory texts on larger screens.

plurals
  1. POnon-virtual template based class - leak memory?
    text
    copied!<p>Based on the <a href="http://rads.stackoverflow.com/amzn/click/0321133544" rel="nofollow">book</a>, pp338</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;ostream&gt; #include &lt;algorithm&gt; #include &lt;boost/function.hpp&gt; #include &lt;boost/bind.hpp&gt; #include &lt;boost/cast.hpp&gt; using namespace std; template &lt;typename R, typename Arg&gt; class invoker_base { public: virtual R operator()(Arg arg)=0; }; template &lt;typename R, typename Arg&gt; class function_ptr_invoker : public invoker_base&lt;R,Arg&gt; { R (*func_)(Arg); public: function_ptr_invoker(R (*func)(Arg)):func_(func) {} R operator()(Arg arg) { return (func_)(arg); } }; template &lt;typename R, typename Arg&gt; class function1 { invoker_base&lt;R,Arg&gt;* invoker_; public: function1(R (*func)(Arg)) : invoker_(new function_ptr_invoker&lt;R,Arg&gt;(func)) {} R operator()(Arg arg) { return (*invoker_)(arg); } ~function1() { delete invoker_; } }; bool some_function(const std::string&amp; s) { std::cout &lt;&lt; s &lt;&lt; " This is really neat\n"; return true; } int main() { function1&lt;bool,const std::string&amp;&gt; f1(&amp;some_function); f1(std::string("Hello")); } </code></pre> <p><strong>Question</strong>> the default destructor of <code>invoker_base</code> is NOT virtual. Does there exist memory leak in the implementation of <code>function1</code>? As the code indicates, the <code>function1::~function1</code> deletes the allocated resource through a non-virtual base class pointer.</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