Browse Source

prototype: pEp::PODStruct - created default alloc/free, and a constructor to provide custom alloc/free

heck-rework
heck 3 years ago
parent
commit
26e0848fa1
  1. 57
      test/test_nr1.cc

57
test/test_nr1.cc

@ -432,24 +432,23 @@ namespace pEp {
PODStruct() = delete; PODStruct() = delete;
// Creates a new instance or binds an existing one // Creates a new instance or binds an existing one
PODStruct(bool is_owner, T** c_struct_pp = nullptr)
{
pEpLogClass("called");
_init(is_owner, c_struct_pp);
}
// Creates a new instance or binds an existing one
// but takes custom alloc/free functions
PODStruct( PODStruct(
bool is_owner, bool is_owner,
std::function<T*()> alloc, std::function<T*()> alloc,
std::function<void(T*)> free, std::function<void(T*)> free,
T** c_struct_pp = nullptr) : T** c_struct_pp = nullptr) :
_alloc(std::move(alloc)), _effective_alloc(std::move(alloc)),
_free(std::move(free)) _effective_free(std::move(free))
{ {
pEpLogClass("called"); _init(is_owner, c_struct_pp);
// if no pp is given, alloc new,
// otherwise bind to it
if (!c_struct_pp) {
_c_struct_p = _alloc();
bind(is_owner, &_c_struct_p);
} else {
bind(is_owner, c_struct_pp);
}
} }
void bind(bool is_owner, T** c_struct_pp) void bind(bool is_owner, T** c_struct_pp)
@ -473,7 +472,7 @@ namespace pEp {
~PODStruct() ~PODStruct()
{ {
if (_is_owner) { if (_is_owner) {
_free(_c_struct_p); _effective_free(_c_struct_p);
} }
} }
@ -501,9 +500,9 @@ namespace pEp {
static bool log_enabled; static bool log_enabled;
protected: private:
const std::function<T*()> _alloc; const std::function<T*()> _effective_alloc{ _alloc };
const std::function<void(T*)> _free; const std::function<void(T*)> _effective_free{ _free };
bool _is_bound{ false }; bool _is_bound{ false };
bool _is_owner{ false }; bool _is_owner{ false };
@ -517,6 +516,32 @@ namespace pEp {
public: public:
explicit Exception(const std::string& msg) : std::runtime_error(msg) {} explicit Exception(const std::string& msg) : std::runtime_error(msg) {}
}; };
void _init(bool is_owner, T** c_struct_pp)
{
// if no pp is given, alloc new,
// otherwise bind to it
if (!c_struct_pp) {
_c_struct_p = _effective_alloc();
bind(is_owner, &_c_struct_p);
} else {
bind(is_owner, c_struct_pp);
}
}
// default alloc/free
static T* _alloc()
{
T* ret = (T*)calloc(1, sizeof(T));
pEpLog(CXX::Inspect::all(ret));
return ret;
}
static void _free(T* ptr)
{
pEpLog(CXX::Inspect::all(ptr));
free(ptr);
}
}; };
// TOOD: // TOOD:

Loading…
Cancel
Save