2013-06-29 33 views
1

我編寫簡單的類表示未經過校正的圖。我想有一個私有類成員 - 指向動態分配的數組集。數組中的每個集合表示與具有相應數組索引號的頂點相鄰的頂點。還有兩個構造函數:一個以數組大小(頂點數)作爲參數,第二個 - 從文件中讀取。 我想使用boost :: shared_ptr來管理分配的內存。 Boost文檔說:保存動態分配數組的C++ shared_ptr

與加速釋放1.53開始,shared_ptr的可以用於一個 指針持有一個動態分配的數組

我創建了一個類成員和兩個構造函數:

boost::shared_ptr<std::set<int>[]> adj; 
... 
Graph(unsigned int vertices); 
Graph(std::ifstream& inputStream); // read 

如何初始化我的shared_ptr,爲第一個構造函數我使用初始化列表:

Graph::Graph(unsigned int vertices) 
     :adj(new std::set<int>[vertices]), 
     vertexCount(vertices){ 
} 

是否正確shared_ptr處理動態分配的數組初始化? Ang當我在第二個構造函數體內收到它的大小時如何初始化shared_ptr?

Graph::Graph(std::ifstream& inputStream){ 
     inputStream >> std::dec >> vertexCount; // read vertex count from file 
     // how to init shared_ptr with vertexCount array size?    
     } 

我可以做得更好嗎?

回答

2

您的共享數組指針看起來不錯。在最後一個構造函數你可以分配一個值使用的shared_ptr的構造函數或函數make_shared(http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/make_shared.html)來調整:

adj = boost::shared_ptr<std::set<int>[]>(new std::set<int>[vertexCount]); 
//or 
adj = boost::make_shared(new std::set<int>[vertexCount]); 

就像你會與正常指針做。

+2

這會呼叫'刪除[]'根據需要? – juanchopanza

1

由於您使用的是boost,因此您可以考慮使用boost::shared_array

boost::shared_array<std::set<int>> set_array; 

替代地,由於boost 1.53,boost::shared_ptr理解動態分配數組:

boost::shared_ptr<std::set<int>[]> set_array(new std::set<int>(N)); 
+0

我剛剛得知shared_ptr學過數組。那麼使用shared_array會有什麼好處呢? –

+0

weak_ptr是否與shared_array一起使用? – 2013-06-29 22:35:33

+0

我剛剛讀了dox(首先我認爲它不能工作:),它意味着全力支持,並且在事後用type_traits思考,將它們聯合起來並不難。由於make_shared返回與[]類型的shared_ptr我希望它只知道沒有自定義刪除的交易。 –