我已經讀過,不能存儲std::auto_ptr
在std::vector
和boost::ptr_vector
可以用來代替。我已經能夠這樣做了,但我不知道如何使用ptr_vector
,當我不想存儲指針時,而是一個結構體,它有一個指針成員。結構域上的智能指針
在這個例子中,我想打開一些文件並將關聯的ofstream
對象與一些額外的數據一起存儲,供以後使用。我想用智能指針替換struct data
的file
字段。由於vector<data> v
應該是所有者,我認爲shared_ptr
可以工作,但不合適。
我應該用什麼替換裸指針file
?
#include <iostream>
#include <fstream>
#include <vector>
struct data {
std::string filename;
std::ofstream* file;
data(const std::string filename, std::ofstream* file)
: filename(filename), file(file)
{
}
};
std::vector<data> open_files()
{
std::vector<data> v;
v.push_back(data("foo", new std::ofstream("foo")));
return v;
}
int main()
{
std::vector<data> v = open_files();
/* use the files */
*(v[0].file) << "foo";
delete v[0].file; // either rely on dtor to close(), or call it manually
}
更新: 我覺得我已經做了在描述我的問題一個次優的工作,讓我試試另一個例子。此外,我要尋找一個C++ 03的解決方案:
#include <memory>
#include <vector>
#include <boost/ptr_container/ptr_vector.hpp>
struct T {
std::auto_ptr<int> a;
};
int main()
{
// instead of
// std::vector<std::auto_ptr<int> > v;
// use
boost::ptr_vector<int> v;
// what to use instead of
// std::vector<T> w;
}
在data的析構函數中做任何需要清理的操作。由於矢量不包含指針,所以你不得不採取任何行動。如果數據的析構函數是正確的,那麼一切都會自行處理。 – juanchopanza
爲什麼你需要一個(不推薦)的auto_ptr?使用boost :: shared_ptr這是可複製的。它將由矢量所有並在矢量離開作用域時銷燬。 –
hhbilly
'auto_ptr'模擬唯一所有權,而'shared_ptr'具有共享所有權的不同含義。如果我有權訪問C++ 11,我會使用'unique_ptr'。但是使用'share_ptr'可能還是比我的版本更好。 –