我有一个清单叫做 mesh_list;
这是一个 boost::ptr_vector<mesh> mesh_list;
现在我要从中删除一个元素。
在网格对象内部,它有1个我从构造函数中更新的指针,它们是:
texture* tex;
现在它是一个普通的指针,在从列表中删除网格元素之前是否必须删除它?
如果将纹理指针更改为shared_ptr,该怎么办?谢谢
Boost指针容器始终拥有其元素。
这意味着他们将始终设法删除这些元素。
指针容器的目的是使您可以拥有运行时多态元素,而不必担心元素的生存期。
但是:mesh
对象所包含的指针是/ just /指针,您需要像往常一样释放它。
任何一个
std::unique_ptr
或boost::scoped_ptr<>
shared_ptr<>
但这几乎总是矫over过正-除非您实际上想共享所有权。下面是一个示范,说明如何scoped_ptr
,unique_ptr
,shared_ptr
都是可以用来类似的效果,而且texture*
意志,本身泄漏(除非您实现对规则的三大mesh
类):
#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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句