何时使用指针和何时不使用? [英] When to use pointers and when not to?
问题描述
我习惯于做Java编程,在编程时你永远不需要考虑指针。但是,目前我正在用C ++编写程序。当做类有其他类的成员时,我应该使用指针,我什么时候不应该?例如,我什么时候想这样做:
class Foo {
Bar b;
}
与此相反:
$ b b
class Foo {
Bar * b;
}
/ p>
在以下情况下使用它们:
- 您要使用 Pimpl idiom ,或抽象工厂
Bar
实例实际上由程序的其他部分管理,而Foo code>类只需要能够访问它。
- 您要推迟
Bar
对象即之后创建 。 -
Bar
实际上是一个基类,您需要该实例为多态。 - 你碰巧使用一个工具包,喜欢将GUI小部件作为指针。示例可以包括(但当然不限于) wxWidgets 和 GLUI 。
在您的业务逻辑中, code> Bar 对象可能不存在;你也可以在Java中使用
null
。不过,请查看 boost :: optional 。 / li> 在任何情况下智能指针,例如 boost :: shared_ptr 。否则,你很可能会忘记释放内存,迟早。一旦你知道你在做什么,考虑一下一个例子什么指针类型是最好的。
(*)任何case - 除了,可能是关于GUI窗口小部件;在这种情况下,您的工具包最有可能为您管理资源
I'm used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I'm writing a program in C++. When making classes that have members of other classes, when should I use pointers and when should I not? For example, when would I want to do this:
class Foo {
Bar b;
}
As opposed to this:
class Foo {
Bar* b;
}
Start by avoiding pointers.
Use them when:
- You want to use the Pimpl idiom, or an abstract factory.
- The
Bar
instance is actually managed by some other part of your program, whereas theFoo
class just needs to be able to access it. - You want to postpone the construction of the
Bar
object (i.e., you want to create it after constructingFoo
). - In your business logic, the
Bar
object may not exist at all; you would usenull
also in Java. However, check out boost::optional as well. Bar
is actually a base class, and you need the instance to be polymorphic.- You happen to be using a toolkit that prefers to present GUI widgets as pointers. Examples could include (but are certainly not limited to) wxWidgets and GLUI.
In any of these cases (*), start by using a smart pointer, such as boost::shared_ptr. Otherwise, you are likely to forget to deallocate the memory, sooner or later. Once you know what you are doing, consider case-by-case what pointer type is best.
(*) any case – except, probably, the bullet regarding GUI widgets; in this case, your toolkit would most probably manage the resources for you as well
这篇关于何时使用指针和何时不使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!