Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement a reference constructor?
    text
    copied!<p>I am looking for a way to have my constructor make a reference to another object in this way:</p> <pre><code>Foo object1("File1"); Foo object2("File1"); </code></pre> <p>The first object is created normally. The second object sees that there is already an object that is using the "File1" parameter and makes itself a reference to the first object. I know this may not be directly possible to do this in this manner. I keep a static vector of Foo* to keep track of the allocated objects.</p> <p>I know that I can make all the members of the class pointers and for the first case create (New) them. In the second case, I would not create them and point them at the first object. Also the second object is guaranteed to have a shorter lifetime than the first.</p> <p>So, is there an easy/elegant way to do this?</p> <p><strong>EDIT:</strong> Thank you for all the great solutions. I like them all, but I can only use one. I will keep all of this knowledge for future reference tho.</p> <p>I am selecting the <code>static map &lt;string, FooObject*&gt;</code> solution. At first I thought it was stupid, but upon further review, it appealed to me as elegant. </p> <p>The only addition that I can see right now would be to add a link counter to the FooObject. This way in the constructor of Foo I can increment the link counter. In the destructor, decrement the counter. If counter is then zero, remove it from the map. This way there is no memory leaks, and the objects can get destructed in any order. I guess this methodology is shared_ptr esque. Credit goes to @Travis for this.</p> <p>Thanks, James.</p>
 

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