Boost logo

Boost :

Subject: Re: [boost] C++ Boost library - passing Shared pointer to a function
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2012-09-09 13:50:02


On Sep 9, 2012 8:34 PM, "abhishek goswami" <zeal_goswami_at_[hidden]> wrote:
>
> I am looking for a project which is converting c malloc/realloc to
shared_ptr. During my Analysis, I found the issue
>
> Can anyone provide me some input how to fix below issue
>
> typedef boost::shared_ptr<Employee_t> srdpointer;
>
> srdpointer
ptr((Employee_t*)malloc(sizeof(Employee_t)),std::ptr_fun(free));

This is only valid if Employee_t is a POD type. Otherwise you also have to
call its destructor.

> How can I achieve the similar functionality using shared ptr as shown in
above code

void allocateBlocks(shared_ptr<int>& ptr, unsigned int& cnt)
{
  ptr.reset((int*)malloc(sizeof(int)*10), &free);
  // also check ptr for NULL here
  cnt = 10;
}

int main()
{
  unsigned int cnt = 0;
  shared_ptr<int> ptr;
  allocateBlocks(ptr, cnt);
}

You can also return ptr from the function, which will simplify usage.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk