Is using std::vector< std> > an antipattern?

后端 未结 4 1316
醉话见心
醉话见心 2020-12-29 22:22

For a long time I was using std::vector and std::shared_ptr hand in hand. Recently I started using std::shared_ptr when

相关标签:
4条回答
  • 2020-12-29 23:01

    1 The problem is not related to shared_ptr<>, but occurs already for ordinary pointers:

    template<typename T>
    void foo(std::vector<const T*>);
    
    int a,b;
    std::vector<int*> bar={&a,&b};
    foo<???>(bar);        // no value for ??? works
    

    2 The construct vector<shared_ptr<T>> is sensibly only iff there is no owner to the objects hold.

    0 讨论(0)
  • 2020-12-29 23:02

    if you insist on keeping std::vector you can try to encapsulate it into a handle-body idiom structure.

    this allows you to keep a non const shared pointer in a const handle.

    0 讨论(0)
  • 2020-12-29 23:07

    I would suggest reviewing your design with a view to establish a clear owner of those object. This is the absence of clear ownership that lead people to use shared smart pointers.

    Bjarne Stroustrup recommends using smart pointers only as a last resort. His recommendations (best to worst) are:

    1. Store an object by value.
    2. Store many objects in a container by value.
    3. If nothing else works, use smart pointers.

    See Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11, and C++14 at 0:37:40.

    0 讨论(0)
  • 2020-12-29 23:23

    It is a valid way of storing immutable (and thus thread safe) objects, a building block for a per-element copy-on-write cache. Definitely not an anti-pattern.

    0 讨论(0)
提交回复
热议问题