1

I find surprising that people that use std::weak_ptr do not find it useful to bind onDelete handlers to their references. I've been looking around in boost but I haven't found anything like this.

Am I missing something? Is a "bad smell" to rely on something like this? or for some reason it is too niche to be generally useful?

lurscher
  • 25,930
  • 29
  • 122
  • 185
  • I don't understand. Wouldn't the destructor of your object get called when the weak pointer is destroyed? Which basically handles onDelete? – Irelia Jul 15 '21 at 02:53
  • @Nina right but the destructor typically contains code that concerns only with the object domain logic resources, the object should not need to know who is listening to uses or changes of usage on smart references of themselves. Handlers for this are typically for consumers and users of the references – lurscher Jul 15 '21 at 03:25
  • I could be misreading this question, but I am aware of no such functionality. Are you proposing it be added? – user4581301 Jul 15 '21 at 04:11
  • just aggregate your object into another one `template class OnDeleter{ public: T object; ~OnDeleter(){/*your stuff here*/} }` – Jeffrey Jul 15 '21 at 04:22
  • @Jeffrey no need to do that, just use a custom deleter, don't think this is what the OP wants though – Alan Birtles Jul 15 '21 at 05:30

1 Answers1

1

The implementation of shared_ptr is basically just a pointer and an atomic reference count, creating and destroying shared_ptr instances just involves incrementing and decrementing the reference count so is pretty fast and requires no mutexes.

In order to implement your scheme the shared_ptr would need to somehow keep track of all weak_ptr instances which would make it much more expensive and probably require a mutex, as this isn't a widely needed requirement it's not worth the cost.

You could use a custom deleter on your shared_ptr and when creating your weak_ptrs use get_deleter to access the deleter and register a callback with it.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60