Search code examples
c++boostweak-ptr

Is it wise to provide access to weak_ptr in a library interface?


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?


Solution

  • If the smart_ptrs are already directly accessible to the library's users, then they've already got access to the weak_ptrs, simply via the corresponding weak_ptr's constructor. But if the smart_ptrs are all internal to the library, that's a different story.

    In that case, I'd recommend letting each object pass out weak_ptrs 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.