How should I wrap C libraries into C++ -


typical c libraries this:

foo_t * foo_open(); int     foo_query( foo_t * ); int     foo_close( foo_t * ); 

i can see 2 ways of wrapping sleak raii structures. either create class , wrap every c function:

class foo { public:    foo(): m_impl( foo_open() ) { }   ~foo() noexcept { foo_close( m_impl ); }    int query() { return foo_query( m_impl ) }; }; 

or use smart pointer custom destructor:

class foo_destructor {  public:     void operator()( foo_t * const obj ) noexcept     {         foo_close( obj );      }  };  typedef std::unique_ptr< foo_t, foo_destructor > foo_ptr; 

and use c interface directly.

int main() {     foo_ptr my_foo( foo_open() );     foo_query( my_foo.get() ); } 

right now, using second solution, because lazy write member functions. there reason why 1 method should preferred other?

the first approach more c++ way of doing things. functions grouped 1 logical unit (the class), you've encapsulated data raii prevents resource leaks , you've managed drop foo_ prefix, too!


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -