Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
Drew Dormann Avatar asked Dec 13 '22 05:12

Drew Dormann


2 Answers

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.

like image 101
Head Geek Avatar answered Apr 28 '23 15:04

Head Geek


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.

like image 20
Nick Veys Avatar answered Apr 28 '23 15:04

Nick Veys