Hello Folks,
at work it happened to me the second time,
that I needed to construct a shared_ptr/weak_ptr to 'this' within the constructor.
This stackoverflow question made think about the situation from the viewpoint of realizability.
I thus went and implemented my own drop-in replacement for shared_ptr, weak_ptr and enable_shared_from_this.
It is linked here:
Outcome:
Obviously, enable_shared_from_this can allow the user to construct a shared_ptr
while still in its ctor and simply pass it the reference_count object that enable_shared_from_this holds to
the shared_ptr that the constructed object will be passed to (after construction). (What a sentence...)
I have tested my apporach and it just works as expected.
This was as far as I'm concerned even acomplished with no speed or size overhead.
My questions now are:
- Has this topic been already discussed somewhere else? What outcome?
- What do you think? Is such usage still dangerous given a very robust implementation with no overhead?
- Is there any use case for it? At least I had it twice now and it looks like, that other people have it as well.
( I know that one could create something using weak_from_raw, but I have not really dug into it yet. )
Beyond: Extending the approach to destructors:
One could argue: "Why not extend it to dtors as well?"
The question is: Is there any use case for this situation?
Because the functionality is perfectly demonstrated in my Library as well.
It works, as long as all shared_/weak_ptrs that get constructed during the dtor
get destroyed before dtor is over.
No duplicate deletion whatsoever - all clean -> it works! (Sadly, allowing this introduces a little bit of overhead :-) )
I'd love to hear your thoughts!
Greetings from Munich,
Jakob