views:

188

answers:

2

That's pretty 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.

+4  A: 

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));
GMan
+1, Really good answer. Beware when creating memory at the place of call (when the called function takes ownership) when more than one operation take place: `foo( bar(), new int(5) )` might leak if `new int(5)` is executed before `bar()` and `bar()` throws an exception. It is safer (even if longer) to use smart pointers: `std::auto_ptr<int> p(new int(5)); foo( bar(), p.release() );` not nice, but safe.
David Rodríguez - dribeas
A: 

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)

pm100
`std::string` is most certainly not a reference counted container.
Dennis Zickefoose
sure it is - the spec does not require it to be but all actual implementations are - including thread safety on the refernce counts just like shared_ptr
pm100
@pm100: I don't think VS/Dinkumware is reference counted.
GMan
There is no way for `std::string` and `shared_ptr<char>` to behave identically no matter what optimizations the library chooses to employ, unless you are dealing with immutable data. And that is a pretty small subset of the uses of smart pointers.
Dennis Zickefoose
Using std::string for this is terrible advice.
Alan