为什么使用指针的向量被认为是坏的? [英] Why is using vector of pointers considered bad?

查看:118
本文介绍了为什么使用指针的向量被认为是坏的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我遇到的意见,我不应该使用指针的向量。
我想知道 - 为什么我不能?

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

例如,如果我有一个类 foo 可以这样做:

For example if I have a class foo it is possible to do this:

vector <foo*> v;
v.push_back(new foo());

我已经看到一些人投票这样的做法,为什么?

I've already seen some people down voting such practices, why is that?

推荐答案

在容器中存储普通指针可能导致内存泄漏和悬空指针。在容器中存储指针不会定义指针的任何种类的所有权。因此,容器不知道描述和复制操作的语义。当从容器中移除元素时,容器不知道如何正确地销毁它们,当复制操作被执行时,没有所有权语义是已知的。当然,你总是可以自己处理这些事情,但是仍然有可能发生人为错误。

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.

这篇关于为什么使用指针的向量被认为是坏的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆