Allocation C for RAII

I have these simple C functions from the library:

struct SAlloc; SAlloc *new_salloc(); void free_salloc(SAlloc *s); 

Is there any way to wrap this in C ++ for a smart pointer (std :: unique_ptr) or otherwise RAII wrappers?

I'm mostly interested in learning about the features of the standard library without creating my own wrapper / class.

+6
source share
4 answers

Yes, you can reuse unique_ptr for this. Just make a customer.

 struct salloc_deleter { void operator()(SAlloc* s) const { free_salloc(s); // what the heck is the return value for? } } using salloc_ptr = std::unique_ptr<SAlloc, salloc_deleter>; 
+13
source

I like the answer of R. Martigno Fernandez, but here is a shorter (but less effective) alternative:

 auto my_alloc = std::shared_ptr<SAlloc>(new_salloc(), free_salloc); 
+3
source

Is there any way to wrap this in C ++ for a smart pointer ( std::unique_ptr ) or otherwise RAII wrappers?

Yes. Here you need a factory function that correctly creates objects that initialize the smart pointer (and ensures that you always correctly create the pointer instances):

 std::shared_ptr<SAlloc> make_shared_salloc() { return std::shared_ptr<SAlloc>(new_salloc(), free_salloc); } // Note: this doesn't work (see comment from @R.MartinhoFernandes below) std::unique_ptr<SAlloc> make_unique_salloc() { return std::unique_ptr<SAlloc>(new_salloc(), free_salloc); } 

You can assign the result of calling these functions to other smart pointers (as needed), and the pointers will be deleted correctly.

Edit: Alternatively, you can specify std::make_shared for your SAlloc.

Edit 2: The second function ( make_unique_salloc ) does not compile. To support the implementation, an alternative delete functor must be implemented.

0
source

Another variation:

 #include <memory> struct SAlloc { int x; }; SAlloc *new_salloc() { return new SAlloc(); } void free_salloc(SAlloc *s) { delete s; } struct salloc_freer { void operator()(SAlloc* s) const { free_salloc(s); } }; typedef std::unique_ptr<SAlloc, salloc_freer> unique_salloc; template<typename... Args> unique_salloc make_salloc(Args&&... args) { auto retval = unique_salloc( new_salloc() ); if(retval) { *retval = SAlloc{std::forward<Args>(args)...}; } return retval; } int main() { unique_salloc u = make_salloc(7); } 

I included the body in SAlloc and various functions to make it http://sscce.org/ - the implementation of these functions is not the case.

As long as you see SAlloc members, the above will allow you to build them, as in the list of initializers, at the same time as you do SAlloc , and if you do not pass any arguments it will nullify all SAlloc struct .

0
source

All Articles