<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>share — Little Step</title>
    <link>https://rex.writeas.com/tag:share</link>
    <description></description>
    <pubDate>Tue, 17 Nov 2026 00:35:53 +0000</pubDate>
    <item>
      <title>Use std::enable\shared\from\_this for this in smart pointer mode</title>
      <link>https://rex.writeas.com/use-std-enablesharedfrom_this-for-this-in-smart-point-mode?pk_campaign=rss-feed</link>
      <description>As we all know that there is a this pointer for all objects, but if we want to use smart pointer, how to we use. It turns out that it&#39;s n...</description>
      <content:encoded><![CDATA[<p>As we all know that there is a <strong>this</strong> pointer for all objects, but if we want to use smart pointer, how to we use.</p>

<p>It turns out that it&#39;s not that easy by creating a share_ptr from this pointer, since we may have many shared_ptrs points to the same object with without knowing each other.</p>

<p>Taking this code as an example, if we create a share_ptr by dangerous function, we will have two share_ptrs pointing to the same object. Both sp1 and sp2 point to same object, and when the two exits it leads problem.</p>

<pre><code class="language-cpp">struct S
{
  shared_ptr&lt;S&gt; dangerous() {
    return shared_ptr&lt;S&gt;(this);  // don&#39;t do this!
  }
};

int main() {
  shared_ptr&lt;S&gt; sp1(new S);
  shared_ptr&lt;S&gt; sp2 = sp-&gt;dangerous();
  return 0;
}
</code></pre>

<p>How to fix this problem, use the <em>std::enable_shared_from_this</em> help class defined in, it is introduced in C++11.</p>

<pre><code class="language-cpp">struct S: enable_shared_from_this&lt;S&gt; {
  shared_ptr&lt;S&gt; dangerous() {
    return shared_from_this();
  }
};

int main() {
  shared_ptr&lt;S&gt; sp1(new S);
  shared_ptr&lt;S&gt; sp2 = sp-&gt;dangerous();  // not dangerous

  return 0;
}
</code></pre>

<p><a href="https://rex.writeas.com/tag:cpp" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">cpp</span></a> <a href="https://rex.writeas.com/tag:share" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">share</span></a>_ptr</p>
]]></content:encoded>
      <guid>https://rex.writeas.com/use-std-enablesharedfrom_this-for-this-in-smart-point-mode</guid>
      <pubDate>Wed, 24 Aug 2022 08:09:16 +0000</pubDate>
    </item>
  </channel>
</rss>