0

I would like to do something like this:

std::wistream input = std::wifstream(text);
if (!input) input = std::wistringstream(text);
// read from input

i.e. have text either interpreted as a filename, or, if no such file exists, use its contents instead of the file's contents.

I could of course use std::wistream * input and then new and delete for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety).

Is there another way of doing this on the stack?

Felix Dombek
  • 13,664
  • 17
  • 79
  • 131
  • You could use a smart pointer such as auto_ptr to handle the allocation/deallocation automatically, depending of course on your later use of the variable. – DeCaf Oct 01 '11 at 18:01
  • Why on freaking earth would someone want to do this ? – Alexandre C. Oct 01 '11 at 18:08
  • @Alexandre C.: Because, generally, I want it to work with files, but for testing I also want to just quickly specify some file content sample in the command-line. – Felix Dombek Oct 01 '11 at 18:12

4 Answers4

2

You could abstract the logic that works with std::wistream& input into a function of its own, and then call it with a std::wifstream or std::wistringstream as appropiate.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
2

I could of course use std::wistream * input and then new and delete for the actual streams. But then, I would have to encapsulate all of this in a class (constructor and destructor, i.e. proper RAII for exception safety).

This is what std::unique_ptr is for. Just use std::unique_ptr<std::istream>.

Alexandre C.
  • 55,948
  • 11
  • 128
  • 197
1

Is there another way of doing this on the stack?

No way.

As the copy-assignment is disabled for all stream classes in C++, you cannot use it.That immediately implies that what you want is not possible.

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

Have you considered auto_ptr or unique_ptr to manage the wistream pointer?

http://www.cplusplus.com/reference/std/memory/auto_ptr/

Max
  • 96
  • 6