1

Why in the following code is the instruction os->operator>> input wrong? Is not the return value of operator>> the object *os?

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
  double input;
  ifstream * os = new ifstream("prova.dat");
  os->operator>> input;
  return 0;
}
5
  • 2
    Don't use pointers to ifstreams! They're not intended to be used that way. They can be passed by reference where necessary. Commented May 12, 2014 at 16:30
  • @Rook what's the specific reason? Commented May 12, 2014 at 16:34
  • 1
    @RoyIacob The same as for any other object shouldn't be used via raw pointer references whenever avoidable. Commented May 12, 2014 at 16:35
  • 1
    Sorry, I thought input was a string. Either os->operator>>(input) or *os >> input works. Commented May 12, 2014 at 16:44
  • 1
    @RoyIacob: the standard classes have all been quite carefully written to handle their own resource creation and cleanup. By creating them on the heap, you lose all of the nice RAII facilities they provide you, you have to take your own responsibility for cleanup and various other things become harder to do. I can't think of any upsides to doing it at all. Commented May 12, 2014 at 17:16

2 Answers 2

5

When you want to use >> as a method, then you need to pass arguments by () like normal functions. To dereference it you should use these two ways:

os->operator >> (input);

or

*os >> input;

Note: Why pointers, when you can use automatic objects or references. Moreover, you need to manage the allocated object and free it.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're creating pointers to streams like that, you're probably doing something wrong.

This should work fine:

int main()
{
  double input;
  std::ifstream os("prova.dat");
  os >> input;
  return 0;
}

Because the ifstream was allocated on the stack, it will be automatically cleaned up when the function finishes, which will close the underlying filehandle. You missed the explicit delete you'd need to do the same in your code.

If you need to pass your stream around, you can do so by reference:

double read_double(std::ifstream& stream)
{
  double d;
  stream >> d;
  return d;
}

int main()
{
  std::ifstream os("prova.dat");
  double input = read_double(os);
  return 0;
}

6 Comments

Well, that's half an answer
@MooingDuck which half?
@Rook The half that doesn't really answer the question.
Right, but I think he was looking for an explanation for why his code didn't work. Telling him the recommended way is still good though.
Fair enough. MM at least has that bit covered, so the OP won't go away empty handed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.