Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unfortunately, what you are asking for is impossible with the traditional interface of smart pointers.</p> <p>The issue is one of lifetime. A <code>weak_ptr</code> cannot be use to access the object directly, because it does not guarantee that said object will live long enough: the object might be pulled right from under your feet.</p> <p>Example:</p> <pre><code>int main() { std::shared_ptr&lt;int&gt; sp(new int(4)); std::weak_ptr&lt;int&gt; wp(sp); if (not wp.expired()) { sp.reset(); std::cout &lt;&lt; *wp &lt;&lt; "\n"; // Access WP ? But there is nothing there! } } </code></pre> <p>Thus, for better or worse, there is <em>no other choice</em> than recovering a shared pointer from the weak pointer any time you actually need to access the object <em>without controlling the duration of this access</em>.</p> <hr> <p>This last point, however, is our clue. A simple idea being to write a well-behaved client of <code>weak_ptr</code> yourself and change the way it allows the external world to access the data. For example:</p> <pre><code>template &lt;typename T&gt; class very_weak_ptr { public: very_weak_ptr() {} explicit very_weak_ptr(std::weak_ptr&lt;T&gt; wp): _wp(wp) {} template &lt;typename F&gt; void apply(F&amp;&amp; f) { std::shared_ptr&lt;T&gt; sp = _wp.lock(); f(sp.get()); } private: std::weak_ptr&lt;T&gt; _wp; }; // class very_weak_ptr </code></pre> <p><em>Note: there is one remaining flaw, <code>enable_shared_from_this</code> allows to recover a <code>std::shared_ptr&lt;T&gt;</code> from the very instance of <code>T</code>; you can add a compile time check on <code>T</code> to prevent usage of this class with such objects.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

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