c++ - How to use smart pointer in this situation -
i want use smart pointer in following situation:
some_struct* ptr = new some_struct; ptr->some_member = new byte[100]; callsomeapi(ptr);
now api can either return error or pass in both cases want delete object , 1 way can write delete statement during error exit , during normal exit.
but how can use smart pointer these pointers ? smart pointers mean unique_ptr, shared_ptr , etc. whichever can work !
thanks!
i assume cannot modify smoe_struct
add destructor it. leaves 2 options: custom deleter, , encapsulation.
first, create custom deleter use std::unique_ptr
:
struct some_struct_deleter { void operator() (some_struct *p) const { delete[] p->some_member; delete p; } }; std::unique_ptr<some_struct, some_struct_deleter> ptr{new some_struct}; ptr->some_member = new byte[100]; callsomeapi(ptr.get());
if find that, unlike situation described in question, shared ownership suit better exclusive one, can use deleter shared_ptr
well, this:
std::shared_ptr<some_struct> ptr{new some_struct, some_struct_deleter{}}; ptr->some_member = new byte[100]; callsomeapi(ptr.get());
a second option, find preferable, wrap some_struct
:
struct some_struct_plus_plus { some_struct s; ~some_struct_plus_plus() { delete[] s.some_member; } some_struct_plus_plus() { s.some_member = new byte[100]; } }; std::unique_ptr<some_struct_plus_plus> ptr{new some_struct_plus_plus}; callsomeapi(&ptr->s);
you "wrap" making some_struct_plus_plus
derive some_struct
instead of aggregating it, give direct access members without need go through s
. @ same time, lead memory leaks if cast some_struct_plus_plus*
some_struct*
, called delete
on it.
Comments
Post a Comment