I am working with the API of a C++ library that takes lots of std::weak_ptr
s as the input parameters of the API methods. The library does not keep these pointers and just does some processing on them. To me, this design is something like this from the library's point of view:
Hi API User,
You have passed me some weak pointers as the input parameter(s) of a method to get a service from the library. But your pointers may be expired and not valid anymore. OK, no problem, I will do the check and let you know about it.
BR, Library API
Isn't it more reasonable for the design of such an API to get all of the pointers using a std::shared_ptr
? In this case, if the API user is working with weak_ptr
s, it is the user's responsibility to .lock()
the weak_ptr
pointers first and then pass them to the API (if the .lock()
is successful). Is there any cases that the API should just get the parameters as the std::weak_ptr
not the std::shared_ptr
?
p.s. There is a similar question here in S.O., but it does not clearly answer my question in general.
If the API methods take a long time to execute then the shared_ptr
s would be locked for the duration of the execution if it took std::shared_ptr
instead of std::weak_ptr
. Whether this is a concern or not is difficult to tell without knowing the API.
I don't see any real disadvantage to this approach, there will be a small cost in converting from shared_ptr
to weak_ptr
and back to shared_ptr
again and certainly a complexity cost in terms of the implementation though as it probably would have to check for null pointers anyway that cost is presumably small.