Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>These are not doing the same thing:</p> <pre><code>ClassA::ClassA(void) : objectB(ClassB( this )), objectC(ClassC( std::make_shared&lt;ClassA&gt;(*this) )) </code></pre> <p>The first initializer creates a temporary of type <code>ClassB</code> with the <code>this</code> pointer and initializes <code>objectB</code> by copying that temporary:</p> <pre><code>objectB(ClassB( this )) </code></pre> <p>The second creates a <em>new</em> <code>ClassA</code> as a copy of <code>*this</code>, stores it in a <code>shared_ptr</code>, then initializes a temporary <code>ClassC</code> with that <code>shared_ptr</code>, then initializes <code>objectC</code> by copying that temporary:</p> <pre><code>objectC(ClassC( std::make_shared&lt;ClassA&gt;(*this) )) </code></pre> <p>Your syntax is unnecessarily verbose, avoid the temporaries and copies and initialize your members directly:</p> <pre><code> objectB( this ), objectC( std::make_shared&lt;ClassA&gt;(*this) ) </code></pre> <p>This is equivalent to:</p> <pre><code> objectB( this ), objectC( std::shared_ptr&lt;ClassA&gt;( new ClassA(*this) ) ) </code></pre> <p>It should be clear that <code>objectB</code> has a pointer to <code>this</code> but <code>objectB</code> has a (shared) pointer to a <em>different</em> object, that is a copy of <code>*this</code>.</p> <p>The point of a <code>shared_ptr</code> is it owns the pointer you give it, and will (generally) delete the pointer. You can't have a <code>shared_ptr</code> that owns <code>this</code> in an object's constructor, because until the object has finished being constructed it can't be owned by any <code>shared_ptr</code> (the pointer you give to a <code>shared_ptr</code> is a pointer to a <em>complete</em> object, not a partially constructed one half way through it's constructor) so there's no safe way to get a <code>shared_ptr</code> referring to <code>this</code> that you can pass to <code>objectC</code>'s constructor. There is a way to do it, using the aliasing feature of <code>shared_ptr</code> but I think you should re-examine your design and ask <em>why</em> you want <code>objectC</code> to "own" the object it's part of ... that doesn't make sense.</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