何时使用C ++中的指针 [英] When to use pointers in C++

查看:94
本文介绍了何时使用C ++中的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习C ++中的指针,我不太确定什么时候使用指针,以及何时使用实际的对象。

I just started learning about pointers in C++, and I'm not very sure on when to use pointers, and when to use actual objects.

例如,在我的一个分配中,我们必须构造一个gPolyline类,其中每个点都由一个gVector定义。现在我的变量为gPolyline类看起来像这样:

For example, in one of my assignments we have to construct a gPolyline class, where each point is defined by a gVector. Right now my variables for the gPolyline class looks like this:

private:
vector<gVector3*> points;

如果我有 gVector3>点,它会有什么不同?此外,是否有一个一般的经验法则,何时使用指针?提前感谢!

If I had vector< gVector3 > points instead, what difference would it make? Also, is there a general rule of thumb for when to use pointers? Thanks in advance!

推荐答案

一般的经验法则是在需要时使用指针,以及值或引用。

The general rule of thumb is to use pointers when you need to, and values or references when you can.

如果使用向量< gVector3> 插入元素将复制这些元素,已连接到您插入的项目。当你存储指针时,向量只是引用你插入的对象。

If you use vector<gVector3> inserting elements will make copies of these elements and the elements will not be connected any more to the item you inserted. When you store pointers, the vector just refers to the object you inserted.

所以如果你想要几个向量共享相同的元素,在所有的向量中,你需要向量来包含指针。如果你不需要这样的功能存储值通常更好,例如它可以让你不用担心什么时候删除所有这些指向对象。

So if you want several vectors to share the same elements, so that changes in the element are reflected in all the vectors, you need the vectors to contain pointers. If you don't need such functionality storing values is usually better, for example it saves you from worrying about when to delete all these pointed to objects.

这篇关于何时使用C ++中的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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