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;
// 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(
bool is_owner,
std::function<T*()> alloc,
std::function<void(T*)> free,
T** c_struct_pp = nullptr) :
_alloc(std::move(alloc)),
_free(std::move(free))
_effective_alloc(std::move(alloc)),
_effective_free(std::move(free))
{
pEpLogClass("called");
// 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);
}
_init(is_owner, c_struct_pp);
}
void bind(bool is_owner, T** c_struct_pp)
@ -473,7 +472,7 @@ namespace pEp {
~PODStruct()
{
if (_is_owner) {
_free(_c_struct_p);
_effective_free(_c_struct_p);
}
}
@ -501,9 +500,9 @@ namespace pEp {
static bool log_enabled;
protected:
const std::function<T*()> _alloc;
const std::function<void(T*)> _free;
private:
const std::function<T*()> _effective_alloc{ _alloc };
const std::function<void(T*)> _effective_free{ _free };
bool _is_bound{ false };
bool _is_owner{ false };
@ -517,6 +516,32 @@ namespace pEp {
public:
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:

Loading…
Cancel
Save