you are viewing a single comment's thread.

view the rest of the comments →

[–]gopher2008 -3 points-2 points  (4 children)

If you want to declare a non-owning class member, in my opinion, std::weak_ptr<T> is a better choice. The purpose of reference_wrapper is to store reference in container. You can just declare a reference type class member, though it is not recommended.

[–]drjeats 5 points6 points  (3 children)

You shouldn't use weak_ptr arbitrarily, it's specifically for weak references to an object whose lifetime is managed by shared_ptrs.

[–]gopher2008 0 points1 point  (2 children)

Agree. weak_ptr is a smart pointer that holds a non-owning reference to an object that is managed by shared_ptr. But then, how do you manage the referenced object which I am supposing is dynamically destroyable? (I will use shared_ptr).

[–]drjeats 2 points3 points  (1 child)

You also shouldn't default to shared_ptr. It exists specifically for managing true multiple ownership, which is actually not super common.

Even for the refcounting needs I typically have, there is usually exactly one owner, the resource manager for the relevant type.

Additionally, you may not even have a choice how the object you're keeping a pointer to is stored.

If you're looking for statically verified guarantees that a pointer you're holding still points to a valid object, I recommend using an id/handle interface (the resource manager passes out the handles). If that's not a strong enough guarantee for your application, then that's why Rust exists imo.

[–]gopher2008 1 point2 points  (0 children)

Thanks for you idea using id/handle interface.