0

假设可以按如下方式创建共享指针

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

我需要传递共享指针,它将分配由 ptr 指向的内存。像这样的东西。

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);
}

如何使用shared_ptr上面的代码实现类似的功能。

4

1 回答 1

-1

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?

于 2012-09-05T13:51:20.617 回答