|
SObjectizer
5.5
|
Sometimes it is necessary to provide some resource to all cooperation's agents. For example: DB connection object or logger object. And that resource must live longer than the lifetime of agents of cooperation. One obvious solution is to use std::shared_ptr or another kind of smart pointer:
It guarantees that logger will be destroyed only after destroying all cooperation agents.
But what if you should use agent which requires reference to logger, not smart pointer? How to control lifetime of that object?
Version 5.2.3 provides two answers for this question.
Since v.5.2.3 it is possible to make a derived class from so_5::rt::agent_coop_t. The only condition for derived classes: its object should be dynamically allocated. It is necessary because SObjectizer Environment takes those objects under control and destroys them by calling delete.
Under this approach cooperation could control object lifetime this way:
And because cooperation lifetime is longer than agents lifetime it is safe to pass reference to logger to agents.
A new method for so_5::rt::agent_coop_t class is introduced in v.5.2.3: take_under_control(). It accepts raw or unique_ptr pointer to dynamically allocated objects and takes this object under control of cooperation. Non limited count of objects could be taken under control of cooperation. They will be destroyed only after destroying agents of cooperation.
With this approach the sample with logger object could be rewritten in the following way:
Strictly speaking the destruction of agents in cooperation destructor depends on agents reference counters. Cooperation holds smart references to its agents. Cooperation decrements reference counters inside smart references in the cooperation’s destructor. In normal situation those counter receives zero value and this leads to agents destruction. But there is a possibility that user receive and store smart reference to an agent somewhere else. In that situation agent will not be destroyed with its cooperation. If the agent will access some external resource via reference/pointer (like logger from example above) anything might happen. But this situation is not under control of SObjectizer. And user should provide appropriate resource lifetime policy in such cases.
1.8.14