std::shared_ptrfully capable of creating and deleting an object with cutstom creator and deleting, but instead newyou should use the creator function.
Consider the following creator and deletion:
typedef struct {
int m_int;
double m_double;
} Foo;
Foo* createObject(int i_val, double d_val) {
Foo* output = (Foo*)malloc(sizeof(Foo));
output->m_int = i_val;
output->m_double = d_val;
puts("Foo created.");
return output;
}
void destroy(Foo* obj) {
free(obj);
puts("Foo destroyed.");
}
To control the instance Foocreated by the above functions, simply follow these steps:
std::shared_ptr<Foo> foo(createObject(32, 3.14), destroy);
Use std::shared_ptris overhead if you do not want to share the property of the property. In this case, it’s std::unique_ptrmuch better, but for this type you have to define a custom delete functor with which it can remove the managed Fooinstance:
struct FooDeleter {
void operator()(Foo* p) const {
destroy(p);
}
};
using FooWrapper = std::unique_ptr<Foo, FooDeleter>;
FooWrapper foo(createObject(32, 3.14));