std::auto_ptr
保存してはstd::vector
ならず、boost::ptr_vector
代わりに使用できることを読みました。ptr_vector
私はそうすることができましたが、ポインターを格納したくない場合にを使用する方法がわかりませんが、ポインターメンバーを持つ構造体です。
この例では、いくつかのファイルを開き、関連付けられたofstream
オブジェクトをいくつかの追加データと共に保存して、後で使用できるようにします。file
のフィールドをstruct data
スマートポインターに置き換えたいと思います。は所有者でなければならないので、vector<data> v
a は機能すると思いますが、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;
}