Why is using vector of pointers considered bad?

前端 未结 6 1492
后悔当初
后悔当初 2020-12-28 21:59

Recently I\'ve met with opinion that I shouldn\'t use vector of pointers. I wanted to know - why I cant?

For example if I have a class foo it is possib

6条回答
  •  春和景丽
    2020-12-28 22:31

    Using an vector of raw pointers is not necessary bad style, as long as you remember that the pointers do not have ownership semantics. When you start using new and delete, it usually means that you're doing something wrong.

    In particular, the only cases where you should use new or delete in modern C++ code is when constructing unique_ptr's, or constructing shared_ptr's with custom deleters.

    For example, assume that we have an class that implemented an bidirectional Graph, a Graph contains some amount of Vertexes.

    class Vertex 
    {
    public: 
        Vertex();
        // raw pointer. No ownership
        std::vector edges;
    }
    
    class Graph 
    {
    public:
        Graph() {};
    
        void addNode() 
        {
            vertexes.push_back(new Vertex); // in C++14: prefer std::make_unique<>
        }
    
    // not shown: our Graph class implements a method to traverse over it's nodes
    private:
        // unique_ptr. Explicit ownership
        std::vector> vertexes;
    }
    
    void connect(Vertex *a, Vertex *b) 
    {
        a->edges.push_back(b);  
        b->edges.push_back(a);
    }
    

    Notice how i have an vector of raw Vertex * in that Vertex class? I can do that because the lifetime of the Vertexes that it points to are managed by the class Graph. The ownership of my Vertex class is explicit from just looking at the code.

    An different answer suggests using shared_ptr's. I personally dislike that approach because shared pointers, in general, make it very hard to reason about the lifetime of objects. In this particular example, shared pointers would not have worked at all because of the circular references between the Vertexes.

提交回复
热议问题