简体   繁体   English

shared_ptr用于原始指针参数

[英]shared_ptr for a raw pointer argument

When the function requires a char*, can you pass in a shared_ptr? 当函数需要char *时,你能传入一个shared_ptr吗?

I'm reading in a whole text file (length = 100), and want to store the char's into a char[] array. 我正在读取整个文本文件(长度= 100),并希望将char存储到char []数组中。 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. 如果在delete []语句之前抛出异常,则会发生内存泄漏。 I'm wondering if I can use shared_ptr readInBuffer(new char[fileLength]); 我想知道我是否可以使用shared_ptr readInBuffer(new char [fileLength]); But the function prototype 但功能原型

read ( char* s, streamsize n ) 读(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. 但它不会编译。

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 shared_ptr that points to an array provokes undefined behaviour, because the smart pointer will delete the pointer, not delete[] it. 大FAT警告 :创建指向数组的shared_ptr会引发未定义的行为,因为智能指针将delete指针,而不是delete[] Use a vector instead! 改为使用vector

Leaving this here because it might serve as a useful warning. 离开这里因为它可能是一个有用的警告。 Original answer follows... 原始答案如下......

The get() function returns the underlying raw pointer. get()函数返回底层的原始指针。 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 . 使用&*readInBuffer相同的结果。

Of course, you have to be certain that dictFile.read() doesn't delete the pointer, or demons might fly out of your nose. 当然,你必须确定dictFile.read()不会delete指针,或者恶魔可能会飞出你的鼻子。

No, you can't pass a shared_ptr . 不,你不能传递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. 但是你可以创建一个,并调用它的get()成员函数来获取传递给函数的原始指针的副本。 However, a shared_ptr doesn't deal with arrays; 但是, shared_ptr不处理数组; that's what vector is for. 这就是vector的用途。 But you can use a unique_ptr to an array to manage that object: 但您可以使用unique_ptr到数组来管理该对象:

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. 写第一行可能有一个较短的方法,但我没有时间去挖掘它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM