Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shared_ptr for a raw pointer argument

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.

like image 590
digit plumber Avatar asked Nov 15 '12 19:11

digit plumber


2 Answers

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.

like image 45
Thomas Avatar answered Oct 05 '22 22:10

Thomas


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

std::vector<char> readInBuffer(fileLength);
dictFile.read(&readInBuffer[0], fileLength);
like image 84
Mark Ransom Avatar answered Oct 05 '22 22:10

Mark Ransom