简体   繁体   中英

C++ Boost library - passing Shared pointer to a function

Assuming shared pointer can be created as follows

typedef boost::shared_ptr<Employee_t> srdpointer;     
srdpointer ptr((Employee_t*)malloc(sizeof(Employee_t)),std::ptr_fun(free));

I need to pass the shared pointer which will allocate memory Pointed by the ptr. Something like this.

void allocateBlocks(int **ptr, int *cnt)
{
    *ptr = (int*)malloc(sizeof(int) * 10);
    *cnt = 10;
    /*do something*/ 
}

int main()
{
    int *p = NULL;
    int count = 0;
    locateBlocks(&p, &count);

    /*do something*/

    free(p);
}

How can I achieve the similar functionality using shared_ptr as shown in above code.

Do you mean something like this?

void allocateBlocks( boost::shared_ptr<int>& out, int& count )
{
  out.reset(new int[...]);
  count = 10;
}

PS: I suggest having a look at boost::shared_array<> & friends for just allocating arrays dynamically.

PS: Would an std::vector<> also do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM