增强PTR矢量擦除一个元素的正确方法



我有一个名为mesh_list;的列表

这是一个boost::ptr_vector<mesh> mesh_list;

现在我想从中删除一个元素。

在网格对象内部,它有 1 个我从构造函数中更新的指针,它们是:

texture* tex;

现在它是一个普通的指针,在从列表中擦除网格元素之前,我必须删除它吗?

如果我将纹理指针更改为shared_ptr,我会得到什么好处?谢谢

提升指针容器始终拥有其元素。

这意味着他们将始终管理这些元素的删除。

指针容器的目的是让您拥有运行时多态元素,而无需担心元素的生存期。

但是mesh对象包含的指针是/just/一个指针,您需要像往常一样释放它。

  • 遵循三法则
  • 使用std::unique_ptrboost::scoped_ptr<>
  • 你可以使用shared_ptr<>但这几乎总是矫枉过正 - 除非你真的想分享所有权。

下面是一个演示,展示了scoped_ptrunique_ptrshared_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
}