Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are right, it is a scooping issue. In the <code>inherit</code> constructor, <code>funcA</code> and <code>funcB</code> are both allocated on the stack and destroyed once the function goes out of scope. The leaves <code>m_map</code> with stale pointers.</p> <p>What you really want is something like</p> <pre><code>inherit::inherit(int lenght, int width, int height) :base(length, width) { m_height = height; // allocated on the heap TSpecificFunctor&lt;inherit&gt; * funcA = new TSpecificFunctor&lt;inherit&gt;(this, &amp;inherit::volume); m_map["a"] = funcA; // allocated on the heap TSpecificFunctor&lt;inherit&gt; * funcB = new TSpecificFunctor&lt;inherit&gt;(this, &amp;inherit::area2); m_map["b"] = funcB; } // when this function exits funcA and funcB are not destroyed </code></pre> <p>But, to avoid any memory leaks, the destructor for <code>inherit</code> will need to clean up the values</p> <pre><code>inherit::~inherit() { for(TestMap::iterator it = m_map.begin(); it != m_map.end(); ++it) { delete it-&gt;second; } } </code></pre> <p>Using <code>new</code> and <code>delete</code> can easily lead to memory leaks. To prevent them, I would suggest looking into smart points like <code>std::unique_ptr</code> and <code>std::shared_ptr</code>. Also, functors are becoming obsolete with the introduction of lambdas in C++11. They are really neat and worth looking into if you are not familiar with them.</p> <hr> <p>If your compiler supports them, to do this with lambdas</p> <pre><code>#include &lt;functional&gt; // ... typedef std::map&lt;std::string, std::function&lt;int(void)&gt;&gt; TestMap; // ... inherit::inherit(int length, int width, int height):base(length, width) { m_height = height; m_map["a"] = [this]() -&gt; int { return volume(); }; m_map["b"] = [this]() -&gt; int { return area2(); }; // can be called like so m_map["a"](); m_map["b"](); } // No need to clean up in destructors </code></pre>
 

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