0

I have two classes, A and B with the following public methods that write/read data to/from an ostream/istream:

class A {
  void print( std::ostream & os = std::cout ) const ; // prints some data
};

class B {
  void read( std::istream & is = std::cin ) ; // reads that data
};

After consulting this thread I used std::stringstreams in the client code to pass data from A to B:

std::stringstream ss;
A a;
B b;

a.print(ss);
b.read(ss);

And it works pretty good. My question is: how could I further optimize this to avoid the copy overhead? I am looking something in the lines of a.read(b.print()), which would naturally require B::print to return a type inheriting both istream and ostream, but any viable solution which would skip the copy overhead would work.

Adama
  • 720
  • 2
  • 5
  • 23
  • 3
    What "copy overhead"? Nothing is being copied here. The parameters are passed by reference. – Sam Varshavchik May 30 '16 at 00:41
  • What would the semantics of `a.read(b.print())` be? It doesn't really make much sense. – uh oh somebody needs a pupper May 30 '16 at 00:45
  • Also, `std::iostream` is what you're looking for as a common type. – uh oh somebody needs a pupper May 30 '16 at 00:45
  • @SamVarshavchik Isn't the ``ostream`` "copied" to the ``stringstream`` in ``b.print(ss)``? Or have I completely misunderstood how streams work? – Adama May 30 '16 at 08:44
  • "copy overhead" is the wrong term. It's used in the context of copying objects, typically as parameters in function calls. Here, you're talking about saving the output in a buffer. In your case, you have one function generating output that's used as input to the second function. The first function is completed first, before the second function starts. The output, from the first function has to go somewhere. It can't magically disappear, only to reappear as input for the second function. Of course, you can run both functions as separate threads, and pass messages, instead of doing this. – Sam Varshavchik May 30 '16 at 10:40
  • It sounds as if you might be asking how to pipe a a C++ `istream` to an `ostream`. It's not easy but [its been done](http://stackoverflow.com/a/12413298/1362568) – Mike Kinghan May 30 '16 at 19:05

0 Answers0