When the function requires a char*, can you pass in a shared_ptr?
I'm reading in a whole text file (length = 100), and want to store the char's into a char[] array. The naive way I used was this:
ifstream dictFile(fileName);
size_t fileLength = 100;
char* readInBuffer(new char[fileLength]);
dictFile.read(readInBuffer, fileLength);
//processing readInBuffuer..............
delete[] readInBuffer;
dictFile.close();
Of course there is memory leak if an exception is thrown before the delete[] statement. I'm wondering if I can use shared_ptr readInBuffer(new char[fileLength]); But the function prototype
read ( char* s, streamsize n )
won't accept a smart pointer as input? Any tricks?
Edit: I'm trying to write something like this:
shared_ptr<char[]> readInBuffer(new char[fileLength]);
dictFile.read(readInBuffer.get(), fileLength);
But it won't compile.
get()
method, but a smart pointer does and it does exactly what you're asking for. – Mark Ransomshared_ptr
isn't smart enough to manage an array. Aunique_ptr
, however, is, if you give it a custom deleter. – Pete Becker