简体   繁体   中英

How do I write a copy constructor for my class which has a std::stringstream member?

If I have a class like this, how should I write the copy constructor?

#include <stringstream>

class MyClass {
  std::stringstream strm;
public:
  MyClass(const MyClass& other){
    //...
  }
  std::string toString() const { return strm.str(); }
};

std::stringstream has no copy constructor itself, so I can't use an initialiser list like this:

MyClass(const MyClass& other): strm(other.strm) {}

你可以试试这个:

MyClass(const MyClass& other): strm(other.strm.str()) {}

If your compiler does not support C++0x, or not want to use move constructor :

MyClass(const MyClass& other)
: strm(other.strm.str())
{
  this->strm.seekg( other.strm.tellg() );
  this->strm.seekp( other.strm.tellp() );
  this->strm.setstate( other.strm.rdstate() );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM