【问题标题】:boost ptr vector correct way to erase one elementboost ptr vector 擦除一个元素的正确方法
【发布时间】:2015-01-30 03:18:52
【问题描述】:

我有一个名为mesh_list;的列表

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

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

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

texture* tex;

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

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

【问题讨论】:

    标签: boost ptr-vector


    【解决方案1】:

    boost 指针容器总是拥有自己的元素。

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

    指针容器的目的是让您可以拥有运行时多态元素而不必担心元素的生命周期。

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

    要么

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

    这里有一个演示,展示了scoped_ptrunique_ptrshared_ptr 都可以达到类似的效果,并且texture* 本身会泄漏(除非您为@987654330 实施三规则@类):

    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
    }
    

    【讨论】:

    • 添加了不同方法的“视觉”演示。您可以使用您最喜欢的堆检查器来验证没有任何智能指针接近泄漏
    猜你喜欢
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 2019-09-09
    • 1970-01-01
    相关资源
    最近更新 更多