Why is using vector of pointers considered bad?

前端 未结 6 1491
后悔当初
后悔当初 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:57

    I will talk specifically about a vector of pointers that's responsible for managing the lifetime of the pointed objects, because that's the only case where a vector of pointers is clearly a questionable choice.

    There are much better alternatives. Specifically:

    std::vector> v;
    

    and

    std::vector> v;
    

    and

    boost::ptr_vector v; // www.boost.org
    

    The above versions tell the user how the lifetime of the objects is taken care of. Using raw pointers instead can possibly lead to the pointers being deleted either more or less than once, especially if the code is modified over time, or if exceptions become involved.

    If you use an interface like ´shared_ptr´ or ´unique_ptr´, this self-documents the lifetime management for the user. When you use raw pointers you have to be clearly document how you handle the lifetime management of the objects, and hope that the right people read the documentation at the right time.

    The benefits of using vectors of raw pointers are that you have more flexibility in how taking care of lifetime management, and that you can possibly get rid of some performance and space overhead.

提交回复
热议问题