简体   繁体   English

C ++ shared_ptr并从类中读取

[英]C++ shared_ptr and reading from the class

I have a problem with simple reading from the file that shares file pointer between a few objects (It works for me with just simple istream, but not when I am using shared pointer of istream pointers). 我有一个简单的问题,即从文件中读取几个对象之间共享文件指针的问题(它对我来说仅适用于简单的istream,但不适用于我使用istream指针的共享指针)。

I am trying to read the whole file to the buffer (file itself is a few lines long. 我正在尝试将整个文件读取到缓冲区(文件本身只有几行。

The code compiles, but throws segmentation fault. 代码可以编译,但是会引发分段错误。

The class that uses shared_ptr: 使用shared_ptr的类:

RecordsSplitter::RecordsSplitter(char *filename):iStream( new ifstream(filename, ifstream::in|ifstream::binary))
{
}


string RecordsSplitter::buildRecord() {
       char *buffer;
        int buffer_length;
        iStream->seekg (0, ios::end)_
        buffer_length = iStream->tellg();
        cout << buffer_length;
        iStream->seekg(0, ios::beg);
        iStream->read(buffer,buffer_length);
        iStream->close();
        cout << buffer;

        return 0;
}







int main(int argc, char* argv[]) {
        RecordsSplitter *splitter;
        splitter = new RecordsSplitter(argv[2]);
        int return_num = splitter->buildRecord();
        return 0;
}

You declare your buffer but you don't initialise it anywhere. 您声明了缓冲区,但是没有在任何地方初始化它。 You need this in your buildRecord function or a use of malloc if you so desire. 如果需要,您buildRecordbuildRecord函数中使用它,或者使用malloc。

buffer = new char[buffer_length];

Your seg fault is caused by this uninitialised pointer 您的段错误是由未初始化的指针引起的

Don't forget to clean up! 别忘了收拾!

delete[] buffer;

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

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