Why is using vector of pointers considered bad?

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

    Storing plain pointers in a container can lead to memory leaks and dangling pointers. Storing a pointer in a container does not define any kind of ownership of the pointer. Thus the container does not know the semantics of desctruction and copy operations. When the elements are being removed from the container the container is not aware how to properly destroy them, when a copy operation is performend no ownership semanctics are known. Of course, you can always handle these things by yourself, but then still a chance of human error is possible.

    Using smart pointers leaves the ownership and destruction semantics up to them.

    Another thing to mention is that containers are divided into non-intrusive and intrusive contaiers - they store the actual provided object instead of a copy so it actually comes down to a collection of pointers. Non intrusive pointers have some advantages, so you can't generalize that pointers in a container is something that should be avoided in all times, still in most cases it is recommended.

提交回复
热议问题