Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As Steve said, you basically want shared_ptr for the construction/destruction part. If you can't use boost, then I'd recommend copying the appropriate code from the boost headers (I believe the license allows this), or whatever other workaround you need to circumvent your dumb corporate policies. The other advantage of this approach is that when you can adopt TR1 or C++0x, you won't need do rewrite/maintain any custom implementation, you can just use the [then] built-in library code.</p> <p>As for the thread safety (which Steve didn't address), I find it's almost always a good idea to use synchronization primitives rather than trying to get it right yourself with custom locking. I'd suggest using a CRITICAL_SECTION, and then adding some timing code to make sure the total lock/unlock time is negligible. Doing a lot of lock/unlock operations is fine, as long as there's not too much contention, and you won't have to debug obscure threaded access issues.</p> <p>That's my advice, anyway, FWIW.</p> <p>Edit: I should add that once you're effectively using boost, you'll probably want to keep a weak_ptr in the MyObject class, so you can check if the extended object still exists on the "get" function without holding a reference to it. This will allow your "ref counted destruction" when no external caller is still using the instance. So, your "get" function looks like:</p> <pre><code>shared_ptr&lt; MyExtendedObject &gt; MyObject::GetExtentedObject(){ RIIALock lock( my_CCriticalSection_instance ); shared_ptr&lt; MyExtendedObject &gt; spObject = my_weak_ptr.lock(); if (spObject) { return spObject; } shared_ptr&lt; MyExtendedObject &gt; spObject = make_shared&lt; MyExtendedObject &gt;(); my_weak_ptr = spObject; return spObject; } </code></pre> <p>... and you don't need a release function, cause that part is done automatically through shared_ptr's reference counting. Hope that's clear.</p> <p>See: <a href="https://stackoverflow.com/questions/2160334/boost-weak-ptrs-in-a-multi-threaded-program-to-implement-a-resource-pool">Boost weak_ptr&#39;s in a multi-threaded program to implement a resource pool</a> for more info on weak_ptr and threading safety.</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