Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Make explicit that library owns pointers

Through the use of smart pointers or not. I'd like to make it explicit to the user of a library that all pointers they pass into the library should now be owned by the library (ie. not released by the user).

Many open source libraries just state it in their documentation that the library owns everything or does not. They discuss expected life time of pointers being passed in. Surely there is a more strict way to convey this information to the user.

An example would be great.

Thanks!

like image 200
Halsafar Avatar asked Dec 30 '25 09:12

Halsafar


1 Answers

Use an owning smart pointer in all your classes, that will take ownership (ie will destroy the object once done with it) and any pointers passed from the users will be taken over by this owning smart pointer.

A good example is std::unique_ptr, once things are done, will destroy it's object.

If you need custom destruction, you can pass it a custom deleter.

Even better is of course to have both creation (ie through make_unique) in your classes too, as you will then have RAII, which will avoid all leaks.

like image 181
Tony The Lion Avatar answered Jan 01 '26 22:01

Tony The Lion