ブースト ポインター コンテナーは、常にその要素を所有します。
これは、これらの要素の削除を常に管理することを意味します。
ポインター コンテナーの目的は、要素の有効期間を気にせずにランタイム ポリモーフィック要素を使用できるようにすることです。
BUT :meshオブジェクトに含まれるポインターは /just/ ポインターであり、いつものように解放する必要があります。
また
- ルール・オブ・スリーに従う
std::unique_ptrまたは_boost::scoped_ptr<>
- 使用できます
shared_ptr<>が、実際に所有権を共有したい場合を除き、ほとんどの場合、やり過ぎです。
scoped_ptr、unique_ptr、shared_ptrをすべて同様の効果に使用する方法を示すデモを次に示します。これは、それ自体でリークします (クラスtexture*に Rule Of Three を実装しない限り)。mesh
Live On Coliru
#include <boost/ptr_container/ptr_vector.hpp>
#include <iostream>
struct texture {
virtual ~texture() {}
virtual void foo() const = 0;
};
struct texA : texture { virtual void foo() const { std::cout << __PRETTY_FUNCTION__ << " "; } };
struct texB : texture { virtual void foo() const { std::cout << __PRETTY_FUNCTION__ << " "; } };
template <typename Pointer> void test() {
struct mesh {
Pointer _ptr;
mesh() : _ptr(new(texA)) {}
mesh(int) : _ptr(new(texB)) {}
void bar() const { _ptr->foo(); }
};
boost::ptr_vector<mesh> meshes;
for (int i=0; i<100; ++i) {
if (rand()%2)
meshes.push_back(new mesh(i));
else
meshes.push_back(new mesh());
}
for (auto& m : meshes)
m.bar();
}
#include <boost/scoped_ptr.hpp>
#include <memory>
int main() {
// non-leaking methods
test<boost::scoped_ptr<texture> >(); // scoped_ptr_mesh
test<std::unique_ptr<texture> >(); // std_mesh
test<std::shared_ptr<texture> >(); // shared_mesh
// uncommenting the next causes textures to be leaked
// test<texture*>(); // leaking_mesh
}