何时使用指针,何时不使用指针 [英] When to use pointers, and when not to use them

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

问题描述

我目前正在用C ++做我的第一个实际项目,因此,对指针来说还很新.我知道它们是什么,并且已经阅读了一些基本的使用规则.可能还不够,因为我仍然不太了解何时以及何时不使用它们.

I'm currently doing my first real project in C++ and so, fairly new to pointers. I know what they are and have read some basic usage rules. Probably not enough since I still do not really understand when to use them, and when not.

问题在于,大多数地方只提到大多数人过度使用或未充分使用它们.我的问题是,何时使用它们,何时不使用?.

The problem is that most places just mention that most people either overuse them or underuse them. My question is, when to use them, and when not?.

当前,在许多情况下,我是在问自己,我应该在这里使用指针还是将变量本身传递给函数.

Currently, in many cases i'm asking myself, should I use a pointer here or just pass the variable itself to the function.

例如,我知道您可以发送一个指向函数的指针,以便该函数实际上可以更改变量本身,而不是变量的副本.但是,当您只需要一次获取对象的某些信息时(例如,该方法需要使用getValue()之类的东西),在这种情况下,指针有用吗?

For instance, I know that you can send a pointer to a function so the function can actually alter the variable itself instead of a copy of it. But when you just need to get some information of the object once (for instance the method needs a getValue() something), are pointers usefull in that case?

我希望看到任何一种反应,但也可能会提供有用的链接.由于这是我第一次使用C ++,所以我还没有一本好的C ++书(如果我继续使用c ++,我正在考虑购买一本书,我可能会考虑).

I would love to see either reactions but also links that might be helpfull. Since it is my first time using C++ I do not yet have a good C++ book (was thinking about buying one if I keep on using c++ which I probably will).

推荐答案

对于C ++的要点:

有效的C ++和更有效的C ++,斯科特·迈耶斯(Scott Meyers).

Effective C++ and More Effective C++ by Scott Meyers.

对于指针(和引用):

  • 如果类型适合4个字节并且不希望在调用返回后更改它,请使用按值传递.
  • 如果类型较大并且您不希望在调用返回后更改它,请使用对const的引用传递.
  • 如果参数不能为NULL,请使用按引用传递
  • 否则使用指针.

如果不需要,不要使用原始指针.在大多数情况下,智能指针(请参见 Boost )是更好的选择.

dont't use raw pointers if you don't need to. Most of the time, a smart pointer (see Boost) is the better option.

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

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