I have a list called mesh_list;
which is a boost::ptr_vector<mesh> mesh_list;
now I want to delete one element from it.
inside of mesh object it has 1 pointer which I newed from constructor,they are:
texture* tex;
now it is a normal pointer, Do I have to delete it before erase the mesh element from list?
what if I change the texture pointer to shared_ptr,what advantage will I get? thanks
The boost Pointer Containers always own their elements.
This implies they will always manage deletion of these elements.
The purpose of the Pointer Containers is so you can have runtime polymorphic elements without worrying about the lifetime of the elements.
BUT: the pointer contained by the mesh
object is /just/ a pointer and you need to free it as always.
Either
std::unique_ptr
or boost::scoped_ptr<>
shared_ptr<>
but that's almost always overkill - unless you actually want to share ownership. Here's a demonstration that shows how scoped_ptr
, unique_ptr
, shared_ptr
can all be used to similar effect, and that texture*
will, by itself, leak (unless you implement Rule Of Three for the mesh
class):
#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
}