我已经读过,不能存储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'可能还是比我的版本更好。 –