2011-03-30 5 views
5

이와 같은 클래스가있는 경우 복사 생성자는 어떻게 작성해야합니까?std :: stringstream 멤버가있는 클래스의 복사본 생성자를 작성하려면 어떻게해야합니까?

#include <stringstream> 

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

표준 : 이제 stringstream은 더 복사 생성자 자체가 없다, 그래서 나는이 같은 initialiser 목록을 사용할 수 없습니다

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

답변

6

당신이 시도 할 수있는 경우

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

이 경우 콘텐츠 만 복사되며 개체의 상태는 복사되지 않습니다. :/ – Naszta

+0

@Naszta : 네, 당신은 당신 자신의 대답에 이것을 암시합니다. 이 답변의 코드는'std :: stringstream'에 어떤 영향을 줍니까? – quamrana

+1

@Naszta : 당신 말이 맞아요. 그러나 스트림을 복사하는 것은 잘 정의 된 작업이 아니므로 작성자에게 컨텍스트 고유의 정의를 제공해야합니다. 예를 들어 복사 된 스트림에서 원본 버퍼와 기본 버퍼를 공유해야하는 경우이를 달성 할 수 없습니다. – ognian

4

당신의 컴파일러가 C++ 0x를 지원하지 않거나 이동 생성자를 사용하지 않으려는 경우 :

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()); 
}; 
+0

한 메모 : C++ 0x의 경우 _move 생성자 _! – Naszta

+0

첫 번째 예제에서 'other.strm'은 이동 생성자에 대해 유효한 인수가 아닙니다. – dalle

+0

@ dalle : http://www.cppreference.com/wiki/io/basic_stringstream/constructor에서 참조를 사용했습니다. C++ 0x 가능 컴파일러가 없습니다. 올바른 양식은 무엇입니까? – Naszta

관련 문제