shared_ptr用于原始指针参数 [英] shared_ptr for a raw pointer argument
问题描述
当函数需要char *时,是否可以传入shared_ptr?
When the function requires a char*, can you pass in a shared_ptr?
我正在读取整个文本文件将字符存储到char []数组中。我使用的天真的方式是:
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();
当然,如果在delete []语句之前抛出异常,我想知道如果我可以使用
shared_ptr readInBuffer(new char [fileLength]);
但函数原型
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)
read ( char* s, streamsize n )
不会接受智能指针作为输入?任何技巧?
won't accept a smart pointer as input? Any tricks?
编辑:我想写如下:
shared_ptr<char[]> readInBuffer(new char[fileLength]);
dictFile.read(readInBuffer.get(), fileLength);
但不会编译。
推荐答案
BIG FAT WARNING :创建指向数组的 shared_ptr
会引发未定义的行为,指针将 delete
指针,而不是 delete []
。使用向量
代替!
BIG FAT WARNING: creating a shared_ptr
that points to an array provokes undefined behaviour, because the smart pointer will delete
the pointer, not delete[]
it. Use a vector
instead!
在这里留下这里,因为它可能作为一个有用的警告。原始答案如下...
Leaving this here because it might serve as a useful warning. Original answer follows...
get()
函数返回底层原始指针。
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);
使用& * readInBuffer
当然,你必须确定 dictFile.read()
code> delete 指针,或者恶魔可能飞出你的鼻子。
Of course, you have to be certain that dictFile.read()
doesn't delete
the pointer, or demons might fly out of your nose.
这篇关于shared_ptr用于原始指针参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!