I have written a library that exposes references to several related object types. All of these objects have their lifetimes managed by the library internally via boost::shared_ptr
A user of the library would also be able to know, by nature of the library, the lifetimes of any of the exposed objects. So they could store pointers or keep references to these objects. It would be reasonable for them to do this and know when those objects are no longer valid.
But I feel guilty forcing my users to be reasonable.
Is it acceptable to have a library expose weak_ptr
's to its objects? Have other libraries done this?
I have profiled this library's usage in apps and have found it to be too mission-critical to expose weak_ptr
exclusively.
Would it be wiser to have matching API functions expose either a reference or a weak_ptr or to make any object capable of exposing a weak_ptr
to itself?
If the smart_ptr
s are already directly accessible to the library's users, then they've already got access to the weak_ptr
s, simply via the corresponding weak_ptr
's constructor. But if the smart_ptr
s are all internal to the library, that's a different story.
In that case, I'd recommend letting each object pass out weak_ptr
s to itself, in addition to any other access your library offers. That gives the users the most flexibility: if they need a weak_ptr
, they've got immediate access to it; if they need a shared_ptr
, they can easily get it; and if they just need access to the object itself, they can ignore the smart pointers entirely.
Of course, I don't know what your library does or how it's used or designed. That might change my recommendation.
Coming up with convoluted mechanisms to get at the objects of your library will only result in people not using your library. If the semantics of the library dictate you need to have people using weak_ptrs, there no way around the user knowing that the objects may go away at some point. Make the interface express as much information about the usage of the library as possible, keeps documentation down and makes it infinitely easier to use.
You can't design around bad/inexperienced users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With