Why is using vector of pointers considered bad?

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

    Because the vector's destructor won't call delete on the pointers, so it's easy to accidentally leak memory. A vector's destructor calls the destructors of all the elements in the vector, but raw pointers don't have destructors.

    However, you can use a vector of smart pointers to ensure that destroying the vector will free the objects in it. vector> can be used in C++11, and in C++98 with TR1 you can use vector> (though shared_ptr has a slight overhead compared to a raw pointer or unique_ptr).

    Boost also has a pointer container library, where the special delete-on-destruction behavior is built into the container itself so you don't need smart pointers.

提交回复
热议问题