How does one create a shared_ptr to pass to a function that takes a void *
That's pre开发者_如何转开发tty much it. I need to allocate memory and pass it to a function that takes a void *. I'd like to use a shared_ptr but I don't know how to do it.
Do you mean something like:
boost::shared_ptr<int> myInt(new int(5));
call_some_function(myInt.get());
This only let's the function use the int*
. It shouldn't try to delete it or take ownership.
If you want just raw memory, use a vector
:
std::vector<char> memory(blockSize);
call_some_function(&blockSize[0]);
Again, the memory belongs to the vector
.
If your function does want ownership, there's no need to wrap it into something, since you won't be managing it:
call_some_function(new int);
call_some_function(new char[blockSize]);
Make sure the function will be releasing it with a call to delete
/delete[]
. If not (for example, it intends to use free()
), you'll need to use malloc
instead:
template <typename T>
T* malloc_new(void)
{
void* memory = std::malloc(sizeof(T));
if (!memory)
throw std::bad_alloc();
try
{
return new (memory) T();
}
catch(...)
{
std::free(memory);
throw;
}
}
call_some_function(malloc_new<int>());
call_some_function(malloc(blockSize));
you can also use std::string as a reference counted memory blob container. It is as efficient as shared_ptr on char * vector (maybe better)
精彩评论