Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is perfectly safe.</p> <p>The following code sample:</p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/shared_ptr.hpp&gt; int main(int, char**) { boost::shared_ptr&lt;int&gt; a(new int(5)); boost::shared_ptr&lt;const int&gt; b = a; std::cout &lt;&lt; "a: " &lt;&lt; a.use_count() &lt;&lt; std::endl; std::cout &lt;&lt; "b: " &lt;&lt; b.use_count() &lt;&lt; std::endl; return EXIT_SUCCESS; } </code></pre> <p>Compiles and run fine, and is perfectly correct. It outputs:</p> <pre><code>a: 2 b: 2 </code></pre> <p>The two <code>shared_ptr</code> share the same reference counter.</p> <hr> <p>Also:</p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/shared_ptr.hpp&gt; class A {}; class B : public A {}; int main(int, char**) { boost::shared_ptr&lt;A&gt; a(new B()); boost::shared_ptr&lt;B&gt; b = boost::static_pointer_cast&lt;B&gt;(a); std::cout &lt;&lt; "a: " &lt;&lt; a.use_count() &lt;&lt; std::endl; std::cout &lt;&lt; "b: " &lt;&lt; b.use_count() &lt;&lt; std::endl; return EXIT_SUCCESS; } </code></pre> <p>Behave the same way. You must, however <strong>never</strong> build your <code>shared_ptr</code> using a construct like this:</p> <pre><code>boost::shared_ptr&lt;A&gt; a(new B()); boost::shared_ptr&lt;B&gt; b(static_cast&lt;B*&gt;(a.get())); </code></pre> <p><code>a.get()</code> gives the raw pointer and loses all information about reference counting. Doing this, you'll end up with two distinct (not linked) <code>shared_ptr</code> that use the same pointer but different reference counters.</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.
    3. 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