shared_ptr for a raw pointer argument

Rather than using a pointer, you can use a vector instead.

std::vector<char> readInBuffer(fileLength);
dictFile.read(&readInBuffer[0], fileLength);

BIG FAT WARNING: creating a std::shared_ptr<char> that points to an array provokes undefined behaviour, because the smart pointer will delete the pointer, not delete[] it. Use a std::shared_ptr<char[]> instead!

Leaving this here because it might serve as a useful warning. Original answer follows...

The get() function returns the underlying raw pointer. You already wrote this in your code!

shared_ptr<char[]> readInBuffer(new char[fileLength]);
dictFile.read(readInBuffer.get(), fileLength);

The same result can be achieved with &*readInBuffer.

Of course, you have to be certain that dictFile.read() doesn't delete the pointer, or demons might fly out of your nose.


No, you can't pass a shared_ptr. But you can create one, and call its get() member function to get a copy of the raw pointer to pass to the function. However, a shared_ptr doesn't deal with arrays; that's what vector is for. But you can use a unique_ptr to an array to manage that object:

std::unique_ptr<char[], std::default_delete<char[]> ptr(new char[whatever]);
f(ptr.get());

There may be a shorter way to write that first line, but I don't have time to dig it out.