0

I have a class with an ifstream pointer as a class member, e.g.

class SomeClass {
      ...
      ifstream* binary_file;
      ...
    public:
      ...
      void randomMethod();
      ...
}

In one of the methods, e.g. randomMethod() I tried to open a file in binary mode by executing binary_file->open(filename, ios::binary);, but this caused a segfault.

I then tried to create a temporary ifstream and then point the pointer to that ifstream like so:

ifstream temp (filename, ios::binary);
binary_file = &temp;

The above code didn't cause a segfault, and I was able to do some processing on the file within this method. However, trying to access it in a different class method, I started to get errors. I presume this is due to the memory that was allocated to temp getting deallocated after the method returns and thus my pointer pointing to an arbitrary memory location.

How can I initialize an ifstream object and keep it attached to my class for later access? (I do attempt to close this file in the deconstuctor but obviously there is nothing to close...)

Thanks!

olnik
  • 1
  • 1
  • 4
    Why do you need to use a pointer at all? Just use a plain `ifstream` object. – Jodocus Mar 26 '18 at 16:07
  • @Jodocus I can't remember exactly what I was doing before but in another method I was getting an error something to do with not being able to copy an ifstream? – olnik Mar 26 '18 at 16:13
  • @olnik hiding the error by using a pointer exposes you to more problems. It's better to understand the error and work out why it's a problem than try and work around it and make a whole new problem – UKMonkey Mar 26 '18 at 16:15

0 Answers0