I have working in large application which contain c and cpp. The all files saved as cpp extension but the code is written in c- style. I mean it is define structure rather than class allocate memory through malloc and realloc and calloc.In recent They have installed boost library So I am planning to use into my existing code base So I have some following question.
- Can I use std::shared_ptr with malloc and free.
- If yes, can anyone point out me sample code base?
- Will it impact any functionality if I create std::shared_ptr in my application and pass this pointer to another function, which uses malloc or calloc?
Or in other words:
How do I achieve the similar functionality with std::shared_ptr, for the following code:
void allocateBlocks(int **ptr, int *cnt)
{
*ptr = (int*)malloc(sizeof(int) * 10);
*cnt = 10;
/*do something*/
}
int main()
{
int *p = NULL;
int count = 0;
allocateBlocks(&p, &count);
/*do something*/
free(p);
}
We call some functions, which accept double pointer and fill the structure inside their application and use malloc. Can we assign those pointer to std::shared_ptr? For example:
typedef struct txn_s
{
int s;
int d;
int *e;
} txn_t;
typedef boost::shared_ptr<txn_t> tpointer;
tpointer((txn_t*)::malloc(sizeof(txn_t),::free));
shared_ptr<T> sp((T*)::malloc(...), ::free)
, depends on how they use the pointer, yes (T* p; fill_p(&p); shared_ptr<T> sp(p, ::free);
). I'd suggest using a hand-writtenscoped_ptr
that allows a deleter, though (akin to howstd::unique_ptr
allows one as a template parameter). – Distributeshared_ptr
is the deleter, aka what is called when the pointer should be freed. – Distribute