Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ copy a stream object

I've been experimenting with C++, and I've come across a problem that I don't know how to solve.

Basically, I've discovered that you can't copy streams (see Why copying stringstream is not allowed?), and that also applies for objects that 'wrap' them. For example:

  • I create a class with a data member of type stringstream.
  • I create an object of this class.
  • I attempt to copy the object, eg "TestObj t1; TestObj t2; t1 = t2;"

This causes the error C2249:

'std::basic_ios<_Elem,_Traits>::operator =' : no accessible path to private member declared in virtual base 'std::basic_ios<_Elem,_Traits>'

So my question is: how can I (preferably easily) copy objects that have data members of type *stream?

Full example code:

#include <iostream>
#include <string>
#include <sstream>

class TestStream
{
public:
    std::stringstream str;
};

int main()
{
    TestStream test;
    TestStream test2;
    test = test2;

    system("pause");
    return 0;
}

Thanks in advance.

UPDATE

I've managed to solve this problem thanks the answers below. What I have done is declare the stream objects once and then simply reference them using pointers in the wrapper objects (eg, TestStream). The same goes for all other objects that have private copy constructors.

like image 288
Matt Larsen Avatar asked Oct 26 '11 14:10

Matt Larsen


1 Answers

The reason you are not allowed to copy a stream is that it doesn't make sense to copy a stream. If you explain what it is that you are trying to do, there's certainly a way to do it. If you want a chunk of data you can copy, use a string. But a stream is more like a connection than a string.

like image 54
David Schwartz Avatar answered Sep 21 '22 05:09

David Schwartz