1

Possible Duplicates:
Why copying stringstream is not allowed?
how copy from one stringstream object to another in C++?

Compiling class T fails with Visual C++ and GCC producing iostreams template errors. Here is the code:

#include <sstream>

class T
{
  static T copy;

  std::ostringstream log;

  T()            {}
  T(const T& t)  {log  = t.log;}
  ~T()           {copy = *this;}
};

T T::copy;

Changing log data member type to string makes it compile and run OK. Is this a legitimate behavior?

Community
  • 1
  • 1
Paul Jurczak
  • 7,008
  • 3
  • 47
  • 72

3 Answers3

4

Copy constructor and copy-assignment of any stream class in C++ has been made private. That means, you cannot make copy of std::ostringstream object:

std::ostringstream ss;

std::ostringstream ss1(ss); //not allowed - copy-constructor is private
ss1=ss; //not allowed - copy-assignment is private
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • OK, that's true, but I'm getting the same error even with empty copy-constructor: `T(const T& t) {}` – Paul Jurczak Aug 13 '11 at 10:49
  • @Paul: Post the actual code, and the error. – Nawaz Aug 13 '11 at 10:55
  • @Nawasz: Code is as in my question above with copy-constructor replaced with: `T(const T& t) {}` or `T(const T& t) {log << t.log.str();}` or `T(const T& t) {log << t.log.rdbuf();}`. I'm always getting: _'std::basic_ios<_Elem,_Traits>::operator =' : no accessible path to private member declared in virtual base 'std::basic_ios<_Elem,_Traits>'_ – Paul Jurczak Aug 13 '11 at 11:06
  • @Paul: Alright. That is because of this line `copy = *this;` which invokes `operator=() generated by the compiler; the generated code has this line `copy.log= (*this).log` which is causing problem. That means, if you comment the line `copy=*this;` then it will compile fine. Atleast that error will not show up. – Nawaz Aug 13 '11 at 11:13
  • Thank you. I fell into copy constructor vs. assignment operator trap. – Paul Jurczak Aug 13 '11 at 11:29
  • @Paul: Its not `copy constructor vs. assignment operator trap`. Its *copy constructor **and** assignment operator trap* which I said in the very beginning of my answer. – Nawaz Aug 13 '11 at 11:32
3

std::ostringstream is not copyable that's why you are getting error. See this answer for more details to know how you can overcome this problem.

T(const T& t)  {log << t.log.rdbuf(); }
Community
  • 1
  • 1
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • It still produces the same error: 'std::basic_ios<_Elem,_Traits>::operator =' : no accessible path to private member declared in virtual base 'std::basic_ios<_Elem,_Traits>' – Paul Jurczak Aug 13 '11 at 10:39
1

I think ostringstream has no overloaded assignment(=) operator.

MetallicPriest
  • 29,191
  • 52
  • 200
  • 356