简体   繁体   中英

Passing shared_ptr to shared object/dll

Suppose I pass a std::shared_ptr from a method func to a so/dll function dll_func , which in turn pushes it into a private dll vector.

Then dll_func returns, and func returns as well, so that the std::shared_ptr in the dll vector is the only std::shared_ptr instance.

If later on the dll clears the vector, the std::shared_ptr in there is deallocated by the dll or by the calling program that initially created the std::shared_ptr ?

The std::shared_ptr will be deleted by whatever function was used as the deleter at the time of its creation. If that function is in the dll, then that will be used; if the function was in the exe, then that one. Assuming you use the default delete , then is is cleared by the standard library runtime ::operator delete but it will be called from the code in the dll (assuming the global is not overridden).

More importantly, when sharing object across the dll boundary, do you use the same compiler and compiler options? If so, then it should all work as expected. If not, don't share objects this way, there is no guarantee around the binary compatibility.

For clarity;

If the std::shared_ptr was created in the exe with no deleter (thus with the default one), the dll will call the same deleter that would have been called from the exe if the last instance was deleted in the exe?

Yes, but that assumes binary compatibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM