shared, weak and lazy pointers in C++
Asked Answered
A

1

13

Is anyone aware of an implementation of shared_ptr and weak_ptr together with a lazy initialization partner? The requirements of the classes were:

  • A lazy_ptr class that allows a client to construct the object later (if at all), without needing the constructor implementation

  • A weak_lazy_ptr class that has three possible states: not yet constructed (won't lock to a shared_ptr), constructed (will lock to a shared_ptr) and destroyed (won't lock to a shared_ptr)

I created some classes that didn't do the job completely a while ago (see CVu article here) that used shared_ptr and weak_ptr in their implementation. The main problems with a model that USES shared and weak pointers instead of integrating with them follow:

  1. Once all lazy_ptr objects go out of scope, any weak references can no longer be locked, even if other clients are holding shared_ptr versions

  2. Construction of objects on different threads can't be controlled

I'd appreciate any pointers to other attempts to reconcile these problems, or to any work in progress there may be in this area.

Apogamy answered 2/12, 2011 at 20:54 Comment(7)
It almost sounds like shared_ptr<boost::optional<T>>, is that right?Verbena
@Apogamy Perhaps you can find more informations here.Peso
@GMan: boost::optional does allow deferred construction, but boost::shared_ptr allows that too, so both are not needed, if I understand you.Serious
@DrewDormann: Not quite. The difference is that when the optional is initialized, all the shared_ptr's refer to the initialized object.Verbena
@GMan: That's right. I didn't think of that scenario.Serious
I have some work in this area in my private stash of code; will post it somewhere under boost license if I manage to dig it out.Suppletion
@Suppletion where could I view your code ?Hodometer
S
2

To create deferred construction that requires no parameters:

boost::bind( boost::factory<T*>(), param1, param2 ) will create a function object that performs the equivalent of new T(param1, param2) without needing the parameters at the time of construction.

To create a shared_ptr that supports this deferred construction:

Bundle your factory with the standard boost::shared_ptr (in a class of your creation, for example), and you'llget the results you describe, including the appropriate weak_ptr functionality...

Whatever code triggers the deferred construction by the client should run:

your_shared_ptr.reset( your_factory() );

Whatever code triggers the object's destruction should run:

your_shared_ptr.reset();

The shared pointer will evauluate to true only during the object's lifetime. And if you want you differentiate "not yet constructed" from "destroyed", you can set a bool after the factory is run.

Serious answered 11/1, 2012 at 22:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.