Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not sure why that definition is not in boost. There must be a good reason (how to deal with lock fail? Is throwing from there acceptable? Thread safety?) Anyway, that will validate your callee.</p> <pre><code>namespace boost { template&lt;class T&gt; T * get_pointer(boost::weak_ptr&lt;T&gt; const&amp; p) { boost::shared_ptr&lt; T &gt; _strong = p.lock(); if( _strong ) return _strong.get(); else throw 1; } } int main(int arg, char *argv[]) { boost::weak_ptr&lt; MyType &gt; weak_bad; { boost::shared_ptr&lt; MyType &gt; strong(new MyType); boost::weak_ptr&lt; MyType &gt; weak(strong); boost::function&lt; void(int) &gt; _func1 = boost::bind(&amp;MyType::setX, weak, _1); _func1(10); weak_bad = strong; } try { boost::function&lt; void(int) &gt; _func1 = boost::bind(&amp;MyType::setX, weak_bad, _1); _func1(10); } catch(...) { std::cout &lt;&lt; "oops!"; } return 0; }; </code></pre> <p>Another solution:</p> <p>You could wrap the std::function. The class producing the callback would hold a shared_ptr&lt; wrapper_type > and provide a weak_ptr&lt; wrapper_type >. The producing object would be the one with the ownership, if it goes out of scope, callers won't be able to promote their weak reference. Your wrapper type could forward call arguments to the std::function or simply expose it via its interface. Just make sure that on copy you properly handle the shared_ptr on the wrapper (don't share).</p> <pre><code>template&lt; typename _Ty &gt; struct wrapper { wrapper(_Ty wrappe) : _wrappe(wrappe) { } _Ty _wrappe; }; ... boost::shared_ptr&lt; wrapper &lt; std::func&lt; ... &gt; &gt; _func(new wrapper &lt; std::func&lt; ... &gt; ); ... boost::weak_ptr&lt; wrapper &lt; std::func&lt; ... &gt; getCallBack() { return _func; } </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