c++ - shared_from_this called from constructor -
I have to register an object on its construction in a container. Without smart pointers I use something like this:
a_class :: a_class () {register_somewhere (this); }
With smart pointers I should use shared_from_this
but I can not use it in the constructor.
Is anyone clean to resolve this problem ? What will you do in a similar situation? I'm thinking of starting a init
method to call after making a composition and put everything in the factory function like this:
boost :: shared_ptr & lt; A_class & gt; Create_a () {boost :: shared_ptr & lt; A_class & gt; PTR (new A_ class); Ptr- & gt; Init (); Return PTR; }
Is it okay or is there a standard procedure to follow in such cases?
Edit: Actually my case is more complex. I have 2 objects that will maintain every other pointers. The truth is that I am not "registering", but to make another object (let's say I am adding this because since you are advising me the design (which is highly appreciated) at least you can know what I am doing: < Pre> In my program there is b_class
) for which it < / Code> parameter is required as
b_class
receives as a weak indicator and stores it.
and a_class :: A_class () {b = new b_class (this); }
b_class
is one of the concrete sections representing the state (in constructor Just the initial state). The a_class
needs an indicator in the current state and b_class
needs to be manipulated in the unit.
A_class
is responsible for creating and creating B_class instances and thus they have a shared_ptr, but b_class
is < Code> a_class , and thus puts a weak indicator a_class
example "existence" b_class
example.
Do you suggest avoiding smart pointers in this case?
b_class
is responsible for creating and deleting examples
a_class
...
a_class
example "existence"b_class
example.
In view of these two facts, there should be no danger that b_class
example a_class
after example a_class < / Code> can try to reach an example
b_class
example to delete the examples a_class
example is responsible because it has been deleted.
b_class
can simply put an indicator on it Associated a_class
example A raw pointer does not express any ownership that is suitable for this case is.
In this example it does not matter how a_class
is created, dynamically, part of a consolidated object, etc. whatever a_class
Creates, manages its lifetime in the same way as a_class
manages the life of this b_class
which gives it immediately.
Example
class a_class; Square b_class {public: b_class (a_class * a_): a (a_) {} private: a_class * a; }; Class a_class {public: a_class (): b (new b_class (it)) {} private: promotion :: share_print & lt; B_class & gt; B; };
Note that there is no need for any shared_ptr
in this toy example, an object member will do the same work (assuming you own Units do not copy the class).
class a_class {public: a_class (): b (this) {} private: b_class b; };
Comments
Post a Comment