2011-03-30 74 views
5

如果我有這樣的類,應該如何編寫複製構造函數?如何爲具有std :: stringstream成員的類編寫複製構造函數?

#include <stringstream> 

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

的std :: stringstream的沒有拷貝構造函數本身,所以我不能使用初始化器列表如下:

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

回答

6

你可以試試這個:

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

在這種情況下,只是內容被複制,對象的狀態不是。 :/ – Naszta 2011-03-30 12:02:11

+0

@Naszta:是的,你暗示這是在你自己的答案中。這個答案中的代碼如何影響'std :: stringstream'? – quamrana 2011-03-30 12:40:03

+1

@Naszta:你是對的。但是,複製流並不是一個明確定義的操作,因此作者應該給它一個特定於上下文的定義。例如,如果您需要複製的流與原始對象共享底層緩衝區,則無法實現它。 – ognian 2011-03-30 12:43:54

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 2011-03-30 11:34:26

+0

在第一個示例中,other.strm不是移動構造函數的有效參數。 – dalle 2011-03-30 12:21:13

+0

@dalle:我使用了http://www.cppreference.com/wiki/io/basic_stringstream/constructor的參考資料我沒有C++ 0x編譯器。什麼是正確的形式? – Naszta 2011-03-30 12:23:45

相關問題